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 manifest;
15mod outline;
16pub mod proto;
17mod syntax_map;
18mod task_context;
19mod text_diff;
20mod toolchain;
21
22#[cfg(test)]
23pub mod buffer_tests;
24
25use crate::language_settings::SoftWrap;
26pub use crate::language_settings::{EditPredictionsMode, IndentGuideSettings};
27use anyhow::{Context as _, Result};
28use async_trait::async_trait;
29use collections::{HashMap, HashSet, IndexSet};
30use futures::Future;
31use futures::future::LocalBoxFuture;
32use futures::lock::OwnedMutexGuard;
33use gpui::{App, AsyncApp, Entity, SharedString};
34pub use highlight_map::HighlightMap;
35use http_client::HttpClient;
36pub use language_registry::{
37 LanguageName, LanguageServerStatusUpdate, LoadedLanguage, ServerHealth,
38};
39use lsp::{
40 CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions, Uri,
41};
42pub use manifest::{ManifestDelegate, ManifestName, ManifestProvider, ManifestQuery};
43use parking_lot::Mutex;
44use regex::Regex;
45use schemars::{JsonSchema, SchemaGenerator, json_schema};
46use semver::Version;
47use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
48use serde_json::Value;
49use settings::WorktreeId;
50use smol::future::FutureExt as _;
51use std::num::NonZeroU32;
52use std::{
53 ffi::OsStr,
54 fmt::Debug,
55 hash::Hash,
56 mem,
57 ops::{DerefMut, Range},
58 path::{Path, PathBuf},
59 str,
60 sync::{
61 Arc, LazyLock,
62 atomic::{AtomicUsize, Ordering::SeqCst},
63 },
64};
65use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
66use task::RunnableTag;
67pub use task_context::{ContextLocation, ContextProvider, RunnableRange};
68pub use text_diff::{
69 DiffOptions, apply_diff_patch, apply_reversed_diff_patch, line_diff, text_diff,
70 text_diff_with_options, unified_diff, unified_diff_with_context, unified_diff_with_offsets,
71 word_diff_ranges,
72};
73use theme::SyntaxTheme;
74pub use toolchain::{
75 LanguageToolchainStore, LocalLanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister,
76 ToolchainMetadata, ToolchainScope,
77};
78use tree_sitter::{self, Query, QueryCursor, WasmStore, wasmtime};
79use util::rel_path::RelPath;
80use util::serde::default_true;
81
82pub use buffer::Operation;
83pub use buffer::*;
84pub use diagnostic_set::{DiagnosticEntry, DiagnosticEntryRef, DiagnosticGroup};
85pub use language_registry::{
86 AvailableLanguage, BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry,
87 QUERY_FILENAME_PREFIXES,
88};
89pub use lsp::{LanguageServerId, LanguageServerName};
90pub use outline::*;
91pub use syntax_map::{
92 OwnedSyntaxLayer, SyntaxLayer, SyntaxMapMatches, ToTreeSitterPoint, TreeSitterOptions,
93};
94pub use text::{AnchorRangeExt, LineEnding};
95pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
96
97static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
98static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
99
100pub fn with_parser<F, R>(func: F) -> R
101where
102 F: FnOnce(&mut Parser) -> R,
103{
104 let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
105 let mut parser = Parser::new();
106 parser
107 .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
108 .unwrap();
109 parser
110 });
111 parser.set_included_ranges(&[]).unwrap();
112 let result = func(&mut parser);
113 PARSERS.lock().push(parser);
114 result
115}
116
117pub fn with_query_cursor<F, R>(func: F) -> R
118where
119 F: FnOnce(&mut QueryCursor) -> R,
120{
121 let mut cursor = QueryCursorHandle::new();
122 func(cursor.deref_mut())
123}
124
125static NEXT_LANGUAGE_ID: AtomicUsize = AtomicUsize::new(0);
126static NEXT_GRAMMAR_ID: AtomicUsize = AtomicUsize::new(0);
127static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
128 wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
129});
130
131/// A shared grammar for plain text, exposed for reuse by downstream crates.
132pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
133 Arc::new(Language::new(
134 LanguageConfig {
135 name: "Plain Text".into(),
136 soft_wrap: Some(SoftWrap::EditorWidth),
137 matcher: LanguageMatcher {
138 path_suffixes: vec!["txt".to_owned()],
139 first_line_pattern: None,
140 },
141 brackets: BracketPairConfig {
142 pairs: vec![
143 BracketPair {
144 start: "(".to_string(),
145 end: ")".to_string(),
146 close: true,
147 surround: true,
148 newline: false,
149 },
150 BracketPair {
151 start: "[".to_string(),
152 end: "]".to_string(),
153 close: true,
154 surround: true,
155 newline: false,
156 },
157 BracketPair {
158 start: "{".to_string(),
159 end: "}".to_string(),
160 close: true,
161 surround: true,
162 newline: false,
163 },
164 BracketPair {
165 start: "\"".to_string(),
166 end: "\"".to_string(),
167 close: true,
168 surround: true,
169 newline: false,
170 },
171 BracketPair {
172 start: "'".to_string(),
173 end: "'".to_string(),
174 close: true,
175 surround: true,
176 newline: false,
177 },
178 ],
179 disabled_scopes_by_bracket_ix: Default::default(),
180 },
181 ..Default::default()
182 },
183 None,
184 ))
185});
186
187/// Types that represent a position in a buffer, and can be converted into
188/// an LSP position, to send to a language server.
189pub trait ToLspPosition {
190 /// Converts the value into an LSP position.
191 fn to_lsp_position(self) -> lsp::Position;
192}
193
194#[derive(Debug, Clone, PartialEq, Eq, Hash)]
195pub struct Location {
196 pub buffer: Entity<Buffer>,
197 pub range: Range<Anchor>,
198}
199
200#[derive(Debug, Clone)]
201pub struct Symbol {
202 pub name: String,
203 pub kind: lsp::SymbolKind,
204 pub container_name: Option<String>,
205}
206
207type ServerBinaryCache = futures::lock::Mutex<Option<(bool, LanguageServerBinary)>>;
208type DownloadableLanguageServerBinary = LocalBoxFuture<'static, Result<LanguageServerBinary>>;
209pub type LanguageServerBinaryLocations = LocalBoxFuture<
210 'static,
211 (
212 Result<LanguageServerBinary>,
213 Option<DownloadableLanguageServerBinary>,
214 ),
215>;
216/// Represents a Language Server, with certain cached sync properties.
217/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
218/// once at startup, and caches the results.
219pub struct CachedLspAdapter {
220 pub name: LanguageServerName,
221 pub disk_based_diagnostic_sources: Vec<String>,
222 pub disk_based_diagnostics_progress_token: Option<String>,
223 language_ids: HashMap<LanguageName, String>,
224 pub adapter: Arc<dyn LspAdapter>,
225 cached_binary: Arc<ServerBinaryCache>,
226}
227
228impl Debug for CachedLspAdapter {
229 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
230 f.debug_struct("CachedLspAdapter")
231 .field("name", &self.name)
232 .field(
233 "disk_based_diagnostic_sources",
234 &self.disk_based_diagnostic_sources,
235 )
236 .field(
237 "disk_based_diagnostics_progress_token",
238 &self.disk_based_diagnostics_progress_token,
239 )
240 .field("language_ids", &self.language_ids)
241 .finish_non_exhaustive()
242 }
243}
244
245impl CachedLspAdapter {
246 pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
247 let name = adapter.name();
248 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
249 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
250 let language_ids = adapter.language_ids();
251
252 Arc::new(CachedLspAdapter {
253 name,
254 disk_based_diagnostic_sources,
255 disk_based_diagnostics_progress_token,
256 language_ids,
257 adapter,
258 cached_binary: Default::default(),
259 })
260 }
261
262 pub fn name(&self) -> LanguageServerName {
263 self.adapter.name()
264 }
265
266 pub async fn get_language_server_command(
267 self: Arc<Self>,
268 delegate: Arc<dyn LspAdapterDelegate>,
269 toolchains: Option<Toolchain>,
270 binary_options: LanguageServerBinaryOptions,
271 cx: &mut AsyncApp,
272 ) -> LanguageServerBinaryLocations {
273 let cached_binary = self.cached_binary.clone().lock_owned().await;
274 self.adapter.clone().get_language_server_command(
275 delegate,
276 toolchains,
277 binary_options,
278 cached_binary,
279 cx.clone(),
280 )
281 }
282
283 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
284 self.adapter.code_action_kinds()
285 }
286
287 pub fn process_diagnostics(
288 &self,
289 params: &mut lsp::PublishDiagnosticsParams,
290 server_id: LanguageServerId,
291 existing_diagnostics: Option<&'_ Buffer>,
292 ) {
293 self.adapter
294 .process_diagnostics(params, server_id, existing_diagnostics)
295 }
296
297 pub fn retain_old_diagnostic(&self, previous_diagnostic: &Diagnostic, cx: &App) -> bool {
298 self.adapter.retain_old_diagnostic(previous_diagnostic, cx)
299 }
300
301 pub fn underline_diagnostic(&self, diagnostic: &lsp::Diagnostic) -> bool {
302 self.adapter.underline_diagnostic(diagnostic)
303 }
304
305 pub fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
306 self.adapter.diagnostic_message_to_markdown(message)
307 }
308
309 pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
310 self.adapter.process_completions(completion_items).await
311 }
312
313 pub async fn labels_for_completions(
314 &self,
315 completion_items: &[lsp::CompletionItem],
316 language: &Arc<Language>,
317 ) -> Result<Vec<Option<CodeLabel>>> {
318 self.adapter
319 .clone()
320 .labels_for_completions(completion_items, language)
321 .await
322 }
323
324 pub async fn labels_for_symbols(
325 &self,
326 symbols: &[Symbol],
327 language: &Arc<Language>,
328 ) -> Result<Vec<Option<CodeLabel>>> {
329 self.adapter
330 .clone()
331 .labels_for_symbols(symbols, language)
332 .await
333 }
334
335 pub fn language_id(&self, language_name: &LanguageName) -> String {
336 self.language_ids
337 .get(language_name)
338 .cloned()
339 .unwrap_or_else(|| language_name.lsp_id())
340 }
341
342 pub async fn initialization_options_schema(
343 &self,
344 delegate: &Arc<dyn LspAdapterDelegate>,
345 cx: &mut AsyncApp,
346 ) -> Option<serde_json::Value> {
347 self.adapter
348 .clone()
349 .initialization_options_schema(
350 delegate,
351 self.cached_binary.clone().lock_owned().await,
352 cx,
353 )
354 .await
355 }
356
357 pub fn process_prompt_response(&self, context: &PromptResponseContext, cx: &mut AsyncApp) {
358 self.adapter.process_prompt_response(context, cx)
359 }
360}
361
362/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
363// e.g. to display a notification or fetch data from the web.
364#[async_trait]
365pub trait LspAdapterDelegate: Send + Sync {
366 fn show_notification(&self, message: &str, cx: &mut App);
367 fn http_client(&self) -> Arc<dyn HttpClient>;
368 fn worktree_id(&self) -> WorktreeId;
369 fn worktree_root_path(&self) -> &Path;
370 fn resolve_executable_path(&self, path: PathBuf) -> PathBuf;
371 fn update_status(&self, language: LanguageServerName, status: BinaryStatus);
372 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>>;
373 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
374
375 async fn npm_package_installed_version(
376 &self,
377 package_name: &str,
378 ) -> Result<Option<(PathBuf, Version)>>;
379 async fn which(&self, command: &OsStr) -> Option<PathBuf>;
380 async fn shell_env(&self) -> HashMap<String, String>;
381 async fn read_text_file(&self, path: &RelPath) -> Result<String>;
382 async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
383}
384
385/// Context provided to LSP adapters when a user responds to a ShowMessageRequest prompt.
386/// This allows adapters to intercept preference selections (like "Always" or "Never")
387/// and potentially persist them to Zed's settings.
388#[derive(Debug, Clone)]
389pub struct PromptResponseContext {
390 /// The original message shown to the user
391 pub message: String,
392 /// The action (button) the user selected
393 pub selected_action: lsp::MessageActionItem,
394}
395
396#[async_trait(?Send)]
397pub trait LspAdapter: 'static + Send + Sync + DynLspInstaller {
398 fn name(&self) -> LanguageServerName;
399
400 fn process_diagnostics(
401 &self,
402 _: &mut lsp::PublishDiagnosticsParams,
403 _: LanguageServerId,
404 _: Option<&'_ Buffer>,
405 ) {
406 }
407
408 /// When processing new `lsp::PublishDiagnosticsParams` diagnostics, whether to retain previous one(s) or not.
409 fn retain_old_diagnostic(&self, _previous_diagnostic: &Diagnostic, _cx: &App) -> bool {
410 false
411 }
412
413 /// Whether to underline a given diagnostic or not, when rendering in the editor.
414 ///
415 /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticTag
416 /// states that
417 /// > Clients are allowed to render diagnostics with this tag faded out instead of having an error squiggle.
418 /// for the unnecessary diagnostics, so do not underline them.
419 fn underline_diagnostic(&self, _diagnostic: &lsp::Diagnostic) -> bool {
420 true
421 }
422
423 /// Post-processes completions provided by the language server.
424 async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
425
426 fn diagnostic_message_to_markdown(&self, _message: &str) -> Option<String> {
427 None
428 }
429
430 async fn labels_for_completions(
431 self: Arc<Self>,
432 completions: &[lsp::CompletionItem],
433 language: &Arc<Language>,
434 ) -> Result<Vec<Option<CodeLabel>>> {
435 let mut labels = Vec::new();
436 for (ix, completion) in completions.iter().enumerate() {
437 let label = self.label_for_completion(completion, language).await;
438 if let Some(label) = label {
439 labels.resize(ix + 1, None);
440 *labels.last_mut().unwrap() = Some(label);
441 }
442 }
443 Ok(labels)
444 }
445
446 async fn label_for_completion(
447 &self,
448 _: &lsp::CompletionItem,
449 _: &Arc<Language>,
450 ) -> Option<CodeLabel> {
451 None
452 }
453
454 async fn labels_for_symbols(
455 self: Arc<Self>,
456 symbols: &[Symbol],
457 language: &Arc<Language>,
458 ) -> Result<Vec<Option<CodeLabel>>> {
459 let mut labels = Vec::new();
460 for (ix, symbol) in symbols.iter().enumerate() {
461 let label = self.label_for_symbol(symbol, language).await;
462 if let Some(label) = label {
463 labels.resize(ix + 1, None);
464 *labels.last_mut().unwrap() = Some(label);
465 }
466 }
467 Ok(labels)
468 }
469
470 async fn label_for_symbol(
471 &self,
472 _symbol: &Symbol,
473 _language: &Arc<Language>,
474 ) -> Option<CodeLabel> {
475 None
476 }
477
478 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
479 async fn initialization_options(
480 self: Arc<Self>,
481 _: &Arc<dyn LspAdapterDelegate>,
482 ) -> Result<Option<Value>> {
483 Ok(None)
484 }
485
486 /// Returns the JSON schema of the initialization_options for the language server.
487 async fn initialization_options_schema(
488 self: Arc<Self>,
489 _delegate: &Arc<dyn LspAdapterDelegate>,
490 _cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
491 _cx: &mut AsyncApp,
492 ) -> Option<serde_json::Value> {
493 None
494 }
495
496 async fn workspace_configuration(
497 self: Arc<Self>,
498 _: &Arc<dyn LspAdapterDelegate>,
499 _: Option<Toolchain>,
500 _: Option<Uri>,
501 _cx: &mut AsyncApp,
502 ) -> Result<Value> {
503 Ok(serde_json::json!({}))
504 }
505
506 async fn additional_initialization_options(
507 self: Arc<Self>,
508 _target_language_server_id: LanguageServerName,
509 _: &Arc<dyn LspAdapterDelegate>,
510 ) -> Result<Option<Value>> {
511 Ok(None)
512 }
513
514 async fn additional_workspace_configuration(
515 self: Arc<Self>,
516 _target_language_server_id: LanguageServerName,
517 _: &Arc<dyn LspAdapterDelegate>,
518 _cx: &mut AsyncApp,
519 ) -> Result<Option<Value>> {
520 Ok(None)
521 }
522
523 /// Returns a list of code actions supported by a given LspAdapter
524 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
525 None
526 }
527
528 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
529 Default::default()
530 }
531
532 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
533 None
534 }
535
536 fn language_ids(&self) -> HashMap<LanguageName, String> {
537 HashMap::default()
538 }
539
540 /// Support custom initialize params.
541 fn prepare_initialize_params(
542 &self,
543 original: InitializeParams,
544 _: &App,
545 ) -> Result<InitializeParams> {
546 Ok(original)
547 }
548
549 /// Method only implemented by the default JSON language server adapter.
550 /// Used to provide dynamic reloading of the JSON schemas used to
551 /// provide autocompletion and diagnostics in Zed setting and keybind
552 /// files
553 fn is_primary_zed_json_schema_adapter(&self) -> bool {
554 false
555 }
556
557 /// True for the extension adapter and false otherwise.
558 fn is_extension(&self) -> bool {
559 false
560 }
561
562 /// Called when a user responds to a ShowMessageRequest from this language server.
563 /// This allows adapters to intercept preference selections (like "Always" or "Never")
564 /// for settings that should be persisted to Zed's settings file.
565 fn process_prompt_response(&self, _context: &PromptResponseContext, _cx: &mut AsyncApp) {}
566}
567
568pub trait LspInstaller {
569 type BinaryVersion;
570 fn check_if_user_installed(
571 &self,
572 _: &dyn LspAdapterDelegate,
573 _: Option<Toolchain>,
574 _: &AsyncApp,
575 ) -> impl Future<Output = Option<LanguageServerBinary>> {
576 async { None }
577 }
578
579 fn fetch_latest_server_version(
580 &self,
581 delegate: &dyn LspAdapterDelegate,
582 pre_release: bool,
583 cx: &mut AsyncApp,
584 ) -> impl Future<Output = Result<Self::BinaryVersion>>;
585
586 fn check_if_version_installed(
587 &self,
588 _version: &Self::BinaryVersion,
589 _container_dir: &PathBuf,
590 _delegate: &dyn LspAdapterDelegate,
591 ) -> impl Send + Future<Output = Option<LanguageServerBinary>> {
592 async { None }
593 }
594
595 fn fetch_server_binary(
596 &self,
597 latest_version: Self::BinaryVersion,
598 container_dir: PathBuf,
599 delegate: &dyn LspAdapterDelegate,
600 ) -> impl Send + Future<Output = Result<LanguageServerBinary>>;
601
602 fn cached_server_binary(
603 &self,
604 container_dir: PathBuf,
605 delegate: &dyn LspAdapterDelegate,
606 ) -> impl Future<Output = Option<LanguageServerBinary>>;
607}
608
609#[async_trait(?Send)]
610pub trait DynLspInstaller {
611 async fn try_fetch_server_binary(
612 &self,
613 delegate: &Arc<dyn LspAdapterDelegate>,
614 container_dir: PathBuf,
615 pre_release: bool,
616 cx: &mut AsyncApp,
617 ) -> Result<LanguageServerBinary>;
618
619 fn get_language_server_command(
620 self: Arc<Self>,
621 delegate: Arc<dyn LspAdapterDelegate>,
622 toolchains: Option<Toolchain>,
623 binary_options: LanguageServerBinaryOptions,
624 cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
625 cx: AsyncApp,
626 ) -> LanguageServerBinaryLocations;
627}
628
629#[async_trait(?Send)]
630impl<LI, BinaryVersion> DynLspInstaller for LI
631where
632 BinaryVersion: Send + Sync,
633 LI: LspInstaller<BinaryVersion = BinaryVersion> + LspAdapter,
634{
635 async fn try_fetch_server_binary(
636 &self,
637 delegate: &Arc<dyn LspAdapterDelegate>,
638 container_dir: PathBuf,
639 pre_release: bool,
640 cx: &mut AsyncApp,
641 ) -> Result<LanguageServerBinary> {
642 let name = self.name();
643
644 log::debug!("fetching latest version of language server {:?}", name.0);
645 delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
646
647 let latest_version = self
648 .fetch_latest_server_version(delegate.as_ref(), pre_release, cx)
649 .await?;
650
651 if let Some(binary) = cx
652 .background_executor()
653 .await_on_background(self.check_if_version_installed(
654 &latest_version,
655 &container_dir,
656 delegate.as_ref(),
657 ))
658 .await
659 {
660 log::debug!("language server {:?} is already installed", name.0);
661 delegate.update_status(name.clone(), BinaryStatus::None);
662 Ok(binary)
663 } else {
664 log::debug!("downloading language server {:?}", name.0);
665 delegate.update_status(name.clone(), BinaryStatus::Downloading);
666 let binary = cx
667 .background_executor()
668 .await_on_background(self.fetch_server_binary(
669 latest_version,
670 container_dir,
671 delegate.as_ref(),
672 ))
673 .await;
674
675 delegate.update_status(name.clone(), BinaryStatus::None);
676 binary
677 }
678 }
679 fn get_language_server_command(
680 self: Arc<Self>,
681 delegate: Arc<dyn LspAdapterDelegate>,
682 toolchain: Option<Toolchain>,
683 binary_options: LanguageServerBinaryOptions,
684 mut cached_binary: OwnedMutexGuard<Option<(bool, LanguageServerBinary)>>,
685 mut cx: AsyncApp,
686 ) -> LanguageServerBinaryLocations {
687 async move {
688 let cached_binary_deref = cached_binary.deref_mut();
689 // First we check whether the adapter can give us a user-installed binary.
690 // If so, we do *not* want to cache that, because each worktree might give us a different
691 // binary:
692 //
693 // worktree 1: user-installed at `.bin/gopls`
694 // worktree 2: user-installed at `~/bin/gopls`
695 // worktree 3: no gopls found in PATH -> fallback to Zed installation
696 //
697 // We only want to cache when we fall back to the global one,
698 // because we don't want to download and overwrite our global one
699 // for each worktree we might have open.
700 if binary_options.allow_path_lookup
701 && let Some(binary) = self
702 .check_if_user_installed(delegate.as_ref(), toolchain, &mut cx)
703 .await
704 {
705 log::info!(
706 "found user-installed language server for {}. path: {:?}, arguments: {:?}",
707 self.name().0,
708 binary.path,
709 binary.arguments
710 );
711 return (Ok(binary), None);
712 }
713
714 if let Some((pre_release, cached_binary)) = cached_binary_deref
715 && *pre_release == binary_options.pre_release
716 {
717 return (Ok(cached_binary.clone()), None);
718 }
719
720 if !binary_options.allow_binary_download {
721 return (
722 Err(anyhow::anyhow!("downloading language servers disabled")),
723 None,
724 );
725 }
726
727 let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await
728 else {
729 return (
730 Err(anyhow::anyhow!("no language server download dir defined")),
731 None,
732 );
733 };
734
735 let last_downloaded_binary = self
736 .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
737 .await
738 .context(
739 "did not find existing language server binary, falling back to downloading",
740 );
741 let download_binary = async move {
742 let mut binary = self
743 .try_fetch_server_binary(
744 &delegate,
745 container_dir.to_path_buf(),
746 binary_options.pre_release,
747 &mut cx,
748 )
749 .await;
750
751 if let Err(error) = binary.as_ref() {
752 if let Some(prev_downloaded_binary) = self
753 .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
754 .await
755 {
756 log::info!(
757 "failed to fetch newest version of language server {:?}. \
758 error: {:?}, falling back to using {:?}",
759 self.name(),
760 error,
761 prev_downloaded_binary.path
762 );
763 binary = Ok(prev_downloaded_binary);
764 } else {
765 delegate.update_status(
766 self.name(),
767 BinaryStatus::Failed {
768 error: format!("{error:?}"),
769 },
770 );
771 }
772 }
773
774 if let Ok(binary) = &binary {
775 *cached_binary = Some((binary_options.pre_release, binary.clone()));
776 }
777
778 binary
779 }
780 .boxed_local();
781 (last_downloaded_binary, Some(download_binary))
782 }
783 .boxed_local()
784 }
785}
786
787#[derive(Clone, Debug, Default, PartialEq, Eq)]
788pub struct CodeLabel {
789 /// The text to display.
790 pub text: String,
791 /// Syntax highlighting runs.
792 pub runs: Vec<(Range<usize>, HighlightId)>,
793 /// The portion of the text that should be used in fuzzy filtering.
794 pub filter_range: Range<usize>,
795}
796
797#[derive(Clone, Debug, Default, PartialEq, Eq)]
798pub struct CodeLabelBuilder {
799 /// The text to display.
800 text: String,
801 /// Syntax highlighting runs.
802 runs: Vec<(Range<usize>, HighlightId)>,
803 /// The portion of the text that should be used in fuzzy filtering.
804 filter_range: Range<usize>,
805}
806
807#[derive(Clone, Deserialize, JsonSchema, Debug)]
808pub struct LanguageConfig {
809 /// Human-readable name of the language.
810 pub name: LanguageName,
811 /// The name of this language for a Markdown code fence block
812 pub code_fence_block_name: Option<Arc<str>>,
813 // The name of the grammar in a WASM bundle (experimental).
814 pub grammar: Option<Arc<str>>,
815 /// The criteria for matching this language to a given file.
816 #[serde(flatten)]
817 pub matcher: LanguageMatcher,
818 /// List of bracket types in a language.
819 #[serde(default)]
820 pub brackets: BracketPairConfig,
821 /// If set to true, auto indentation uses last non empty line to determine
822 /// the indentation level for a new line.
823 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
824 pub auto_indent_using_last_non_empty_line: bool,
825 // Whether indentation of pasted content should be adjusted based on the context.
826 #[serde(default)]
827 pub auto_indent_on_paste: Option<bool>,
828 /// A regex that is used to determine whether the indentation level should be
829 /// increased in the following line.
830 #[serde(default, deserialize_with = "deserialize_regex")]
831 #[schemars(schema_with = "regex_json_schema")]
832 pub increase_indent_pattern: Option<Regex>,
833 /// A regex that is used to determine whether the indentation level should be
834 /// decreased in the following line.
835 #[serde(default, deserialize_with = "deserialize_regex")]
836 #[schemars(schema_with = "regex_json_schema")]
837 pub decrease_indent_pattern: Option<Regex>,
838 /// A list of rules for decreasing indentation. Each rule pairs a regex with a set of valid
839 /// "block-starting" tokens. When a line matches a pattern, its indentation is aligned with
840 /// the most recent line that began with a corresponding token. This enables context-aware
841 /// outdenting, like aligning an `else` with its `if`.
842 #[serde(default)]
843 pub decrease_indent_patterns: Vec<DecreaseIndentConfig>,
844 /// A list of characters that trigger the automatic insertion of a closing
845 /// bracket when they immediately precede the point where an opening
846 /// bracket is inserted.
847 #[serde(default)]
848 pub autoclose_before: String,
849 /// A placeholder used internally by Semantic Index.
850 #[serde(default)]
851 pub collapsed_placeholder: String,
852 /// A line comment string that is inserted in e.g. `toggle comments` action.
853 /// A language can have multiple flavours of line comments. All of the provided line comments are
854 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
855 #[serde(default)]
856 pub line_comments: Vec<Arc<str>>,
857 /// Delimiters and configuration for recognizing and formatting block comments.
858 #[serde(default)]
859 pub block_comment: Option<BlockCommentConfig>,
860 /// Delimiters and configuration for recognizing and formatting documentation comments.
861 #[serde(default, alias = "documentation")]
862 pub documentation_comment: Option<BlockCommentConfig>,
863 /// List markers that are inserted unchanged on newline (e.g., `- `, `* `, `+ `).
864 #[serde(default)]
865 pub unordered_list: Vec<Arc<str>>,
866 /// Configuration for ordered lists with auto-incrementing numbers on newline (e.g., `1. ` becomes `2. `).
867 #[serde(default)]
868 pub ordered_list: Vec<OrderedListConfig>,
869 /// Configuration for task lists where multiple markers map to a single continuation prefix (e.g., `- [x] ` continues as `- [ ] `).
870 #[serde(default)]
871 pub task_list: Option<TaskListConfig>,
872 /// A list of additional regex patterns that should be treated as prefixes
873 /// for creating boundaries during rewrapping, ensuring content from one
874 /// prefixed section doesn't merge with another (e.g., markdown list items).
875 /// By default, Zed treats as paragraph and comment prefixes as boundaries.
876 #[serde(default, deserialize_with = "deserialize_regex_vec")]
877 #[schemars(schema_with = "regex_vec_json_schema")]
878 pub rewrap_prefixes: Vec<Regex>,
879 /// A list of language servers that are allowed to run on subranges of a given language.
880 #[serde(default)]
881 pub scope_opt_in_language_servers: Vec<LanguageServerName>,
882 #[serde(default)]
883 pub overrides: HashMap<String, LanguageConfigOverride>,
884 /// A list of characters that Zed should treat as word characters for the
885 /// purpose of features that operate on word boundaries, like 'move to next word end'
886 /// or a whole-word search in buffer search.
887 #[serde(default)]
888 pub word_characters: HashSet<char>,
889 /// Whether to indent lines using tab characters, as opposed to multiple
890 /// spaces.
891 #[serde(default)]
892 pub hard_tabs: Option<bool>,
893 /// How many columns a tab should occupy.
894 #[serde(default)]
895 #[schemars(range(min = 1, max = 128))]
896 pub tab_size: Option<NonZeroU32>,
897 /// How to soft-wrap long lines of text.
898 #[serde(default)]
899 pub soft_wrap: Option<SoftWrap>,
900 /// When set, selections can be wrapped using prefix/suffix pairs on both sides.
901 #[serde(default)]
902 pub wrap_characters: Option<WrapCharactersConfig>,
903 /// The name of a Prettier parser that will be used for this language when no file path is available.
904 /// If there's a parser name in the language settings, that will be used instead.
905 #[serde(default)]
906 pub prettier_parser_name: Option<String>,
907 /// If true, this language is only for syntax highlighting via an injection into other
908 /// languages, but should not appear to the user as a distinct language.
909 #[serde(default)]
910 pub hidden: bool,
911 /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
912 #[serde(default)]
913 pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
914 /// A list of characters that Zed should treat as word characters for completion queries.
915 #[serde(default)]
916 pub completion_query_characters: HashSet<char>,
917 /// A list of characters that Zed should treat as word characters for linked edit operations.
918 #[serde(default)]
919 pub linked_edit_characters: HashSet<char>,
920 /// A list of preferred debuggers for this language.
921 #[serde(default)]
922 pub debuggers: IndexSet<SharedString>,
923 /// A list of import namespace segments that aren't expected to appear in file paths. For
924 /// example, "super" and "crate" in Rust.
925 #[serde(default)]
926 pub ignored_import_segments: HashSet<Arc<str>>,
927 /// Regular expression that matches substrings to omit from import paths, to make the paths more
928 /// similar to how they are specified when imported. For example, "/mod\.rs$" or "/__init__\.py$".
929 #[serde(default, deserialize_with = "deserialize_regex")]
930 #[schemars(schema_with = "regex_json_schema")]
931 pub import_path_strip_regex: Option<Regex>,
932}
933
934#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
935pub struct DecreaseIndentConfig {
936 #[serde(default, deserialize_with = "deserialize_regex")]
937 #[schemars(schema_with = "regex_json_schema")]
938 pub pattern: Option<Regex>,
939 #[serde(default)]
940 pub valid_after: Vec<String>,
941}
942
943/// Configuration for continuing ordered lists with auto-incrementing numbers.
944#[derive(Clone, Debug, Deserialize, JsonSchema)]
945pub struct OrderedListConfig {
946 /// A regex pattern with a capture group for the number portion (e.g., `(\\d+)\\. `).
947 pub pattern: String,
948 /// A format string where `{1}` is replaced with the incremented number (e.g., `{1}. `).
949 pub format: String,
950}
951
952/// Configuration for continuing task lists on newline.
953#[derive(Clone, Debug, Deserialize, JsonSchema)]
954pub struct TaskListConfig {
955 /// The list markers to match (e.g., `- [ ] `, `- [x] `).
956 pub prefixes: Vec<Arc<str>>,
957 /// The marker to insert when continuing the list on a new line (e.g., `- [ ] `).
958 pub continuation: Arc<str>,
959}
960
961#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
962pub struct LanguageMatcher {
963 /// 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`.
964 #[serde(default)]
965 pub path_suffixes: Vec<String>,
966 /// A regex pattern that determines whether the language should be assigned to a file or not.
967 #[serde(
968 default,
969 serialize_with = "serialize_regex",
970 deserialize_with = "deserialize_regex"
971 )]
972 #[schemars(schema_with = "regex_json_schema")]
973 pub first_line_pattern: Option<Regex>,
974}
975
976/// The configuration for JSX tag auto-closing.
977#[derive(Clone, Deserialize, JsonSchema, Debug)]
978pub struct JsxTagAutoCloseConfig {
979 /// The name of the node for a opening tag
980 pub open_tag_node_name: String,
981 /// The name of the node for an closing tag
982 pub close_tag_node_name: String,
983 /// The name of the node for a complete element with children for open and close tags
984 pub jsx_element_node_name: String,
985 /// The name of the node found within both opening and closing
986 /// tags that describes the tag name
987 pub tag_name_node_name: String,
988 /// Alternate Node names for tag names.
989 /// Specifically needed as TSX represents the name in `<Foo.Bar>`
990 /// as `member_expression` rather than `identifier` as usual
991 #[serde(default)]
992 pub tag_name_node_name_alternates: Vec<String>,
993 /// Some grammars are smart enough to detect a closing tag
994 /// that is not valid i.e. doesn't match it's corresponding
995 /// opening tag or does not have a corresponding opening tag
996 /// This should be set to the name of the node for invalid
997 /// closing tags if the grammar contains such a node, otherwise
998 /// detecting already closed tags will not work properly
999 #[serde(default)]
1000 pub erroneous_close_tag_node_name: Option<String>,
1001 /// See above for erroneous_close_tag_node_name for details
1002 /// This should be set if the node used for the tag name
1003 /// within erroneous closing tags is different from the
1004 /// normal tag name node name
1005 #[serde(default)]
1006 pub erroneous_close_tag_name_node_name: Option<String>,
1007}
1008
1009/// The configuration for block comments for this language.
1010#[derive(Clone, Debug, JsonSchema, PartialEq)]
1011pub struct BlockCommentConfig {
1012 /// A start tag of block comment.
1013 pub start: Arc<str>,
1014 /// A end tag of block comment.
1015 pub end: Arc<str>,
1016 /// A character to add as a prefix when a new line is added to a block comment.
1017 pub prefix: Arc<str>,
1018 /// A indent to add for prefix and end line upon new line.
1019 #[schemars(range(min = 1, max = 128))]
1020 pub tab_size: u32,
1021}
1022
1023impl<'de> Deserialize<'de> for BlockCommentConfig {
1024 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1025 where
1026 D: Deserializer<'de>,
1027 {
1028 #[derive(Deserialize)]
1029 #[serde(untagged)]
1030 enum BlockCommentConfigHelper {
1031 New {
1032 start: Arc<str>,
1033 end: Arc<str>,
1034 prefix: Arc<str>,
1035 tab_size: u32,
1036 },
1037 Old([Arc<str>; 2]),
1038 }
1039
1040 match BlockCommentConfigHelper::deserialize(deserializer)? {
1041 BlockCommentConfigHelper::New {
1042 start,
1043 end,
1044 prefix,
1045 tab_size,
1046 } => Ok(BlockCommentConfig {
1047 start,
1048 end,
1049 prefix,
1050 tab_size,
1051 }),
1052 BlockCommentConfigHelper::Old([start, end]) => Ok(BlockCommentConfig {
1053 start,
1054 end,
1055 prefix: "".into(),
1056 tab_size: 0,
1057 }),
1058 }
1059 }
1060}
1061
1062/// Represents a language for the given range. Some languages (e.g. HTML)
1063/// interleave several languages together, thus a single buffer might actually contain
1064/// several nested scopes.
1065#[derive(Clone, Debug)]
1066pub struct LanguageScope {
1067 language: Arc<Language>,
1068 override_id: Option<u32>,
1069}
1070
1071#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
1072pub struct LanguageConfigOverride {
1073 #[serde(default)]
1074 pub line_comments: Override<Vec<Arc<str>>>,
1075 #[serde(default)]
1076 pub block_comment: Override<BlockCommentConfig>,
1077 #[serde(skip)]
1078 pub disabled_bracket_ixs: Vec<u16>,
1079 #[serde(default)]
1080 pub word_characters: Override<HashSet<char>>,
1081 #[serde(default)]
1082 pub completion_query_characters: Override<HashSet<char>>,
1083 #[serde(default)]
1084 pub linked_edit_characters: Override<HashSet<char>>,
1085 #[serde(default)]
1086 pub opt_into_language_servers: Vec<LanguageServerName>,
1087 #[serde(default)]
1088 pub prefer_label_for_snippet: Option<bool>,
1089}
1090
1091#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
1092#[serde(untagged)]
1093pub enum Override<T> {
1094 Remove { remove: bool },
1095 Set(T),
1096}
1097
1098impl<T> Default for Override<T> {
1099 fn default() -> Self {
1100 Override::Remove { remove: false }
1101 }
1102}
1103
1104impl<T> Override<T> {
1105 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
1106 match this {
1107 Some(Self::Set(value)) => Some(value),
1108 Some(Self::Remove { remove: true }) => None,
1109 Some(Self::Remove { remove: false }) | None => original,
1110 }
1111 }
1112}
1113
1114impl Default for LanguageConfig {
1115 fn default() -> Self {
1116 Self {
1117 name: LanguageName::new_static(""),
1118 code_fence_block_name: None,
1119 grammar: None,
1120 matcher: LanguageMatcher::default(),
1121 brackets: Default::default(),
1122 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
1123 auto_indent_on_paste: None,
1124 increase_indent_pattern: Default::default(),
1125 decrease_indent_pattern: Default::default(),
1126 decrease_indent_patterns: Default::default(),
1127 autoclose_before: Default::default(),
1128 line_comments: Default::default(),
1129 block_comment: Default::default(),
1130 documentation_comment: Default::default(),
1131 unordered_list: Default::default(),
1132 ordered_list: Default::default(),
1133 task_list: Default::default(),
1134 rewrap_prefixes: Default::default(),
1135 scope_opt_in_language_servers: Default::default(),
1136 overrides: Default::default(),
1137 word_characters: Default::default(),
1138 collapsed_placeholder: Default::default(),
1139 hard_tabs: None,
1140 tab_size: None,
1141 soft_wrap: None,
1142 wrap_characters: None,
1143 prettier_parser_name: None,
1144 hidden: false,
1145 jsx_tag_auto_close: None,
1146 completion_query_characters: Default::default(),
1147 linked_edit_characters: Default::default(),
1148 debuggers: Default::default(),
1149 ignored_import_segments: Default::default(),
1150 import_path_strip_regex: None,
1151 }
1152 }
1153}
1154
1155#[derive(Clone, Debug, Deserialize, JsonSchema)]
1156pub struct WrapCharactersConfig {
1157 /// Opening token split into a prefix and suffix. The first caret goes
1158 /// after the prefix (i.e., between prefix and suffix).
1159 pub start_prefix: String,
1160 pub start_suffix: String,
1161 /// Closing token split into a prefix and suffix. The second caret goes
1162 /// after the prefix (i.e., between prefix and suffix).
1163 pub end_prefix: String,
1164 pub end_suffix: String,
1165}
1166
1167fn auto_indent_using_last_non_empty_line_default() -> bool {
1168 true
1169}
1170
1171fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
1172 let source = Option::<String>::deserialize(d)?;
1173 if let Some(source) = source {
1174 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
1175 } else {
1176 Ok(None)
1177 }
1178}
1179
1180fn regex_json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1181 json_schema!({
1182 "type": "string"
1183 })
1184}
1185
1186fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
1187where
1188 S: Serializer,
1189{
1190 match regex {
1191 Some(regex) => serializer.serialize_str(regex.as_str()),
1192 None => serializer.serialize_none(),
1193 }
1194}
1195
1196fn deserialize_regex_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Regex>, D::Error> {
1197 let sources = Vec::<String>::deserialize(d)?;
1198 sources
1199 .into_iter()
1200 .map(|source| regex::Regex::new(&source))
1201 .collect::<Result<_, _>>()
1202 .map_err(de::Error::custom)
1203}
1204
1205fn regex_vec_json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
1206 json_schema!({
1207 "type": "array",
1208 "items": { "type": "string" }
1209 })
1210}
1211
1212#[doc(hidden)]
1213#[cfg(any(test, feature = "test-support"))]
1214pub struct FakeLspAdapter {
1215 pub name: &'static str,
1216 pub initialization_options: Option<Value>,
1217 pub prettier_plugins: Vec<&'static str>,
1218 pub disk_based_diagnostics_progress_token: Option<String>,
1219 pub disk_based_diagnostics_sources: Vec<String>,
1220 pub language_server_binary: LanguageServerBinary,
1221
1222 pub capabilities: lsp::ServerCapabilities,
1223 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
1224 pub label_for_completion: Option<
1225 Box<
1226 dyn 'static
1227 + Send
1228 + Sync
1229 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
1230 >,
1231 >,
1232}
1233
1234/// Configuration of handling bracket pairs for a given language.
1235///
1236/// This struct includes settings for defining which pairs of characters are considered brackets and
1237/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
1238#[derive(Clone, Debug, Default, JsonSchema)]
1239#[schemars(with = "Vec::<BracketPairContent>")]
1240pub struct BracketPairConfig {
1241 /// A list of character pairs that should be treated as brackets in the context of a given language.
1242 pub pairs: Vec<BracketPair>,
1243 /// A list of tree-sitter scopes for which a given bracket should not be active.
1244 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
1245 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
1246}
1247
1248impl BracketPairConfig {
1249 pub fn is_closing_brace(&self, c: char) -> bool {
1250 self.pairs.iter().any(|pair| pair.end.starts_with(c))
1251 }
1252}
1253
1254#[derive(Deserialize, JsonSchema)]
1255pub struct BracketPairContent {
1256 #[serde(flatten)]
1257 pub bracket_pair: BracketPair,
1258 #[serde(default)]
1259 pub not_in: Vec<String>,
1260}
1261
1262impl<'de> Deserialize<'de> for BracketPairConfig {
1263 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1264 where
1265 D: Deserializer<'de>,
1266 {
1267 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1268 let (brackets, disabled_scopes_by_bracket_ix) = result
1269 .into_iter()
1270 .map(|entry| (entry.bracket_pair, entry.not_in))
1271 .unzip();
1272
1273 Ok(BracketPairConfig {
1274 pairs: brackets,
1275 disabled_scopes_by_bracket_ix,
1276 })
1277 }
1278}
1279
1280/// Describes a single bracket pair and how an editor should react to e.g. inserting
1281/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1282#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1283pub struct BracketPair {
1284 /// Starting substring for a bracket.
1285 pub start: String,
1286 /// Ending substring for a bracket.
1287 pub end: String,
1288 /// True if `end` should be automatically inserted right after `start` characters.
1289 pub close: bool,
1290 /// True if selected text should be surrounded by `start` and `end` characters.
1291 #[serde(default = "default_true")]
1292 pub surround: bool,
1293 /// True if an extra newline should be inserted while the cursor is in the middle
1294 /// of that bracket pair.
1295 pub newline: bool,
1296}
1297
1298#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1299pub struct LanguageId(usize);
1300
1301impl LanguageId {
1302 pub(crate) fn new() -> Self {
1303 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1304 }
1305}
1306
1307pub struct Language {
1308 pub(crate) id: LanguageId,
1309 pub(crate) config: LanguageConfig,
1310 pub(crate) grammar: Option<Arc<Grammar>>,
1311 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1312 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1313 pub(crate) manifest_name: Option<ManifestName>,
1314}
1315
1316#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1317pub struct GrammarId(pub usize);
1318
1319impl GrammarId {
1320 pub(crate) fn new() -> Self {
1321 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1322 }
1323}
1324
1325pub struct Grammar {
1326 id: GrammarId,
1327 pub ts_language: tree_sitter::Language,
1328 pub(crate) error_query: Option<Query>,
1329 pub highlights_config: Option<HighlightsConfig>,
1330 pub(crate) brackets_config: Option<BracketsConfig>,
1331 pub(crate) redactions_config: Option<RedactionConfig>,
1332 pub(crate) runnable_config: Option<RunnableConfig>,
1333 pub(crate) indents_config: Option<IndentConfig>,
1334 pub outline_config: Option<OutlineConfig>,
1335 pub text_object_config: Option<TextObjectConfig>,
1336 pub(crate) injection_config: Option<InjectionConfig>,
1337 pub(crate) override_config: Option<OverrideConfig>,
1338 pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1339 pub(crate) imports_config: Option<ImportsConfig>,
1340 pub(crate) highlight_map: Mutex<HighlightMap>,
1341}
1342
1343pub struct HighlightsConfig {
1344 pub query: Query,
1345 pub identifier_capture_indices: Vec<u32>,
1346}
1347
1348struct IndentConfig {
1349 query: Query,
1350 indent_capture_ix: u32,
1351 start_capture_ix: Option<u32>,
1352 end_capture_ix: Option<u32>,
1353 outdent_capture_ix: Option<u32>,
1354 suffixed_start_captures: HashMap<u32, SharedString>,
1355}
1356
1357pub struct OutlineConfig {
1358 pub query: Query,
1359 pub item_capture_ix: u32,
1360 pub name_capture_ix: u32,
1361 pub context_capture_ix: Option<u32>,
1362 pub extra_context_capture_ix: Option<u32>,
1363 pub open_capture_ix: Option<u32>,
1364 pub close_capture_ix: Option<u32>,
1365 pub annotation_capture_ix: Option<u32>,
1366}
1367
1368#[derive(Debug, Clone, Copy, PartialEq)]
1369pub enum DebuggerTextObject {
1370 Variable,
1371 Scope,
1372}
1373
1374impl DebuggerTextObject {
1375 pub fn from_capture_name(name: &str) -> Option<DebuggerTextObject> {
1376 match name {
1377 "debug-variable" => Some(DebuggerTextObject::Variable),
1378 "debug-scope" => Some(DebuggerTextObject::Scope),
1379 _ => None,
1380 }
1381 }
1382}
1383
1384#[derive(Debug, Clone, Copy, PartialEq)]
1385pub enum TextObject {
1386 InsideFunction,
1387 AroundFunction,
1388 InsideClass,
1389 AroundClass,
1390 InsideComment,
1391 AroundComment,
1392}
1393
1394impl TextObject {
1395 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1396 match name {
1397 "function.inside" => Some(TextObject::InsideFunction),
1398 "function.around" => Some(TextObject::AroundFunction),
1399 "class.inside" => Some(TextObject::InsideClass),
1400 "class.around" => Some(TextObject::AroundClass),
1401 "comment.inside" => Some(TextObject::InsideComment),
1402 "comment.around" => Some(TextObject::AroundComment),
1403 _ => None,
1404 }
1405 }
1406
1407 pub fn around(&self) -> Option<Self> {
1408 match self {
1409 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1410 TextObject::InsideClass => Some(TextObject::AroundClass),
1411 TextObject::InsideComment => Some(TextObject::AroundComment),
1412 _ => None,
1413 }
1414 }
1415}
1416
1417pub struct TextObjectConfig {
1418 pub query: Query,
1419 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1420}
1421
1422struct InjectionConfig {
1423 query: Query,
1424 content_capture_ix: u32,
1425 language_capture_ix: Option<u32>,
1426 patterns: Vec<InjectionPatternConfig>,
1427}
1428
1429struct RedactionConfig {
1430 pub query: Query,
1431 pub redaction_capture_ix: u32,
1432}
1433
1434#[derive(Clone, Debug, PartialEq)]
1435enum RunnableCapture {
1436 Named(SharedString),
1437 Run,
1438}
1439
1440struct RunnableConfig {
1441 pub query: Query,
1442 /// A mapping from capture indice to capture kind
1443 pub extra_captures: Vec<RunnableCapture>,
1444}
1445
1446struct OverrideConfig {
1447 query: Query,
1448 values: HashMap<u32, OverrideEntry>,
1449}
1450
1451#[derive(Debug)]
1452struct OverrideEntry {
1453 name: String,
1454 range_is_inclusive: bool,
1455 value: LanguageConfigOverride,
1456}
1457
1458#[derive(Default, Clone)]
1459struct InjectionPatternConfig {
1460 language: Option<Box<str>>,
1461 combined: bool,
1462}
1463
1464#[derive(Debug)]
1465struct BracketsConfig {
1466 query: Query,
1467 open_capture_ix: u32,
1468 close_capture_ix: u32,
1469 patterns: Vec<BracketsPatternConfig>,
1470}
1471
1472#[derive(Clone, Debug, Default)]
1473struct BracketsPatternConfig {
1474 newline_only: bool,
1475 rainbow_exclude: bool,
1476}
1477
1478pub struct DebugVariablesConfig {
1479 pub query: Query,
1480 pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1481}
1482
1483pub struct ImportsConfig {
1484 pub query: Query,
1485 pub import_ix: u32,
1486 pub name_ix: Option<u32>,
1487 pub namespace_ix: Option<u32>,
1488 pub source_ix: Option<u32>,
1489 pub list_ix: Option<u32>,
1490 pub wildcard_ix: Option<u32>,
1491 pub alias_ix: Option<u32>,
1492}
1493
1494impl Language {
1495 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1496 Self::new_with_id(LanguageId::new(), config, ts_language)
1497 }
1498
1499 pub fn id(&self) -> LanguageId {
1500 self.id
1501 }
1502
1503 fn new_with_id(
1504 id: LanguageId,
1505 config: LanguageConfig,
1506 ts_language: Option<tree_sitter::Language>,
1507 ) -> Self {
1508 Self {
1509 id,
1510 config,
1511 grammar: ts_language.map(|ts_language| {
1512 Arc::new(Grammar {
1513 id: GrammarId::new(),
1514 highlights_config: None,
1515 brackets_config: None,
1516 outline_config: None,
1517 text_object_config: None,
1518 indents_config: None,
1519 injection_config: None,
1520 override_config: None,
1521 redactions_config: None,
1522 runnable_config: None,
1523 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1524 debug_variables_config: None,
1525 imports_config: None,
1526 ts_language,
1527 highlight_map: Default::default(),
1528 })
1529 }),
1530 context_provider: None,
1531 toolchain: None,
1532 manifest_name: None,
1533 }
1534 }
1535
1536 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1537 self.context_provider = provider;
1538 self
1539 }
1540
1541 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1542 self.toolchain = provider;
1543 self
1544 }
1545
1546 pub fn with_manifest(mut self, name: Option<ManifestName>) -> Self {
1547 self.manifest_name = name;
1548 self
1549 }
1550
1551 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1552 if let Some(query) = queries.highlights {
1553 self = self
1554 .with_highlights_query(query.as_ref())
1555 .context("Error loading highlights query")?;
1556 }
1557 if let Some(query) = queries.brackets {
1558 self = self
1559 .with_brackets_query(query.as_ref())
1560 .context("Error loading brackets query")?;
1561 }
1562 if let Some(query) = queries.indents {
1563 self = self
1564 .with_indents_query(query.as_ref())
1565 .context("Error loading indents query")?;
1566 }
1567 if let Some(query) = queries.outline {
1568 self = self
1569 .with_outline_query(query.as_ref())
1570 .context("Error loading outline query")?;
1571 }
1572 if let Some(query) = queries.injections {
1573 self = self
1574 .with_injection_query(query.as_ref())
1575 .context("Error loading injection query")?;
1576 }
1577 if let Some(query) = queries.overrides {
1578 self = self
1579 .with_override_query(query.as_ref())
1580 .context("Error loading override query")?;
1581 }
1582 if let Some(query) = queries.redactions {
1583 self = self
1584 .with_redaction_query(query.as_ref())
1585 .context("Error loading redaction query")?;
1586 }
1587 if let Some(query) = queries.runnables {
1588 self = self
1589 .with_runnable_query(query.as_ref())
1590 .context("Error loading runnables query")?;
1591 }
1592 if let Some(query) = queries.text_objects {
1593 self = self
1594 .with_text_object_query(query.as_ref())
1595 .context("Error loading textobject query")?;
1596 }
1597 if let Some(query) = queries.debugger {
1598 self = self
1599 .with_debug_variables_query(query.as_ref())
1600 .context("Error loading debug variables query")?;
1601 }
1602 if let Some(query) = queries.imports {
1603 self = self
1604 .with_imports_query(query.as_ref())
1605 .context("Error loading imports query")?;
1606 }
1607 Ok(self)
1608 }
1609
1610 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1611 let grammar = self.grammar_mut()?;
1612 let query = Query::new(&grammar.ts_language, source)?;
1613
1614 let mut identifier_capture_indices = Vec::new();
1615 for name in [
1616 "variable",
1617 "constant",
1618 "constructor",
1619 "function",
1620 "function.method",
1621 "function.method.call",
1622 "function.special",
1623 "property",
1624 "type",
1625 "type.interface",
1626 ] {
1627 identifier_capture_indices.extend(query.capture_index_for_name(name));
1628 }
1629
1630 grammar.highlights_config = Some(HighlightsConfig {
1631 query,
1632 identifier_capture_indices,
1633 });
1634
1635 Ok(self)
1636 }
1637
1638 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1639 let grammar = self.grammar_mut()?;
1640
1641 let query = Query::new(&grammar.ts_language, source)?;
1642 let extra_captures: Vec<_> = query
1643 .capture_names()
1644 .iter()
1645 .map(|&name| match name {
1646 "run" => RunnableCapture::Run,
1647 name => RunnableCapture::Named(name.to_string().into()),
1648 })
1649 .collect();
1650
1651 grammar.runnable_config = Some(RunnableConfig {
1652 extra_captures,
1653 query,
1654 });
1655
1656 Ok(self)
1657 }
1658
1659 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1660 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1661 let mut item_capture_ix = 0;
1662 let mut name_capture_ix = 0;
1663 let mut context_capture_ix = None;
1664 let mut extra_context_capture_ix = None;
1665 let mut open_capture_ix = None;
1666 let mut close_capture_ix = None;
1667 let mut annotation_capture_ix = None;
1668 if populate_capture_indices(
1669 &query,
1670 &self.config.name,
1671 "outline",
1672 &[],
1673 &mut [
1674 Capture::Required("item", &mut item_capture_ix),
1675 Capture::Required("name", &mut name_capture_ix),
1676 Capture::Optional("context", &mut context_capture_ix),
1677 Capture::Optional("context.extra", &mut extra_context_capture_ix),
1678 Capture::Optional("open", &mut open_capture_ix),
1679 Capture::Optional("close", &mut close_capture_ix),
1680 Capture::Optional("annotation", &mut annotation_capture_ix),
1681 ],
1682 ) {
1683 self.grammar_mut()?.outline_config = Some(OutlineConfig {
1684 query,
1685 item_capture_ix,
1686 name_capture_ix,
1687 context_capture_ix,
1688 extra_context_capture_ix,
1689 open_capture_ix,
1690 close_capture_ix,
1691 annotation_capture_ix,
1692 });
1693 }
1694 Ok(self)
1695 }
1696
1697 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1698 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1699
1700 let mut text_objects_by_capture_ix = Vec::new();
1701 for (ix, name) in query.capture_names().iter().enumerate() {
1702 if let Some(text_object) = TextObject::from_capture_name(name) {
1703 text_objects_by_capture_ix.push((ix as u32, text_object));
1704 } else {
1705 log::warn!(
1706 "unrecognized capture name '{}' in {} textobjects TreeSitter query",
1707 name,
1708 self.config.name,
1709 );
1710 }
1711 }
1712
1713 self.grammar_mut()?.text_object_config = Some(TextObjectConfig {
1714 query,
1715 text_objects_by_capture_ix,
1716 });
1717 Ok(self)
1718 }
1719
1720 pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1721 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1722
1723 let mut objects_by_capture_ix = Vec::new();
1724 for (ix, name) in query.capture_names().iter().enumerate() {
1725 if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1726 objects_by_capture_ix.push((ix as u32, text_object));
1727 } else {
1728 log::warn!(
1729 "unrecognized capture name '{}' in {} debugger TreeSitter query",
1730 name,
1731 self.config.name,
1732 );
1733 }
1734 }
1735
1736 self.grammar_mut()?.debug_variables_config = Some(DebugVariablesConfig {
1737 query,
1738 objects_by_capture_ix,
1739 });
1740 Ok(self)
1741 }
1742
1743 pub fn with_imports_query(mut self, source: &str) -> Result<Self> {
1744 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1745
1746 let mut import_ix = 0;
1747 let mut name_ix = None;
1748 let mut namespace_ix = None;
1749 let mut source_ix = None;
1750 let mut list_ix = None;
1751 let mut wildcard_ix = None;
1752 let mut alias_ix = None;
1753 if populate_capture_indices(
1754 &query,
1755 &self.config.name,
1756 "imports",
1757 &[],
1758 &mut [
1759 Capture::Required("import", &mut import_ix),
1760 Capture::Optional("name", &mut name_ix),
1761 Capture::Optional("namespace", &mut namespace_ix),
1762 Capture::Optional("source", &mut source_ix),
1763 Capture::Optional("list", &mut list_ix),
1764 Capture::Optional("wildcard", &mut wildcard_ix),
1765 Capture::Optional("alias", &mut alias_ix),
1766 ],
1767 ) {
1768 self.grammar_mut()?.imports_config = Some(ImportsConfig {
1769 query,
1770 import_ix,
1771 name_ix,
1772 namespace_ix,
1773 source_ix,
1774 list_ix,
1775 wildcard_ix,
1776 alias_ix,
1777 });
1778 }
1779 return Ok(self);
1780 }
1781
1782 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1783 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1784 let mut open_capture_ix = 0;
1785 let mut close_capture_ix = 0;
1786 if populate_capture_indices(
1787 &query,
1788 &self.config.name,
1789 "brackets",
1790 &[],
1791 &mut [
1792 Capture::Required("open", &mut open_capture_ix),
1793 Capture::Required("close", &mut close_capture_ix),
1794 ],
1795 ) {
1796 let patterns = (0..query.pattern_count())
1797 .map(|ix| {
1798 let mut config = BracketsPatternConfig::default();
1799 for setting in query.property_settings(ix) {
1800 let setting_key = setting.key.as_ref();
1801 if setting_key == "newline.only" {
1802 config.newline_only = true
1803 }
1804 if setting_key == "rainbow.exclude" {
1805 config.rainbow_exclude = true
1806 }
1807 }
1808 config
1809 })
1810 .collect();
1811 self.grammar_mut()?.brackets_config = Some(BracketsConfig {
1812 query,
1813 open_capture_ix,
1814 close_capture_ix,
1815 patterns,
1816 });
1817 }
1818 Ok(self)
1819 }
1820
1821 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1822 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1823 let mut indent_capture_ix = 0;
1824 let mut start_capture_ix = None;
1825 let mut end_capture_ix = None;
1826 let mut outdent_capture_ix = None;
1827 if populate_capture_indices(
1828 &query,
1829 &self.config.name,
1830 "indents",
1831 &["start."],
1832 &mut [
1833 Capture::Required("indent", &mut indent_capture_ix),
1834 Capture::Optional("start", &mut start_capture_ix),
1835 Capture::Optional("end", &mut end_capture_ix),
1836 Capture::Optional("outdent", &mut outdent_capture_ix),
1837 ],
1838 ) {
1839 let mut suffixed_start_captures = HashMap::default();
1840 for (ix, name) in query.capture_names().iter().enumerate() {
1841 if let Some(suffix) = name.strip_prefix("start.") {
1842 suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1843 }
1844 }
1845
1846 self.grammar_mut()?.indents_config = Some(IndentConfig {
1847 query,
1848 indent_capture_ix,
1849 start_capture_ix,
1850 end_capture_ix,
1851 outdent_capture_ix,
1852 suffixed_start_captures,
1853 });
1854 }
1855 Ok(self)
1856 }
1857
1858 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1859 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1860 let mut language_capture_ix = None;
1861 let mut injection_language_capture_ix = None;
1862 let mut content_capture_ix = None;
1863 let mut injection_content_capture_ix = None;
1864 if populate_capture_indices(
1865 &query,
1866 &self.config.name,
1867 "injections",
1868 &[],
1869 &mut [
1870 Capture::Optional("language", &mut language_capture_ix),
1871 Capture::Optional("injection.language", &mut injection_language_capture_ix),
1872 Capture::Optional("content", &mut content_capture_ix),
1873 Capture::Optional("injection.content", &mut injection_content_capture_ix),
1874 ],
1875 ) {
1876 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1877 (None, Some(ix)) => Some(ix),
1878 (Some(_), Some(_)) => {
1879 anyhow::bail!("both language and injection.language captures are present");
1880 }
1881 _ => language_capture_ix,
1882 };
1883 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1884 (None, Some(ix)) => Some(ix),
1885 (Some(_), Some(_)) => {
1886 anyhow::bail!("both content and injection.content captures are present")
1887 }
1888 _ => content_capture_ix,
1889 };
1890 let patterns = (0..query.pattern_count())
1891 .map(|ix| {
1892 let mut config = InjectionPatternConfig::default();
1893 for setting in query.property_settings(ix) {
1894 match setting.key.as_ref() {
1895 "language" | "injection.language" => {
1896 config.language.clone_from(&setting.value);
1897 }
1898 "combined" | "injection.combined" => {
1899 config.combined = true;
1900 }
1901 _ => {}
1902 }
1903 }
1904 config
1905 })
1906 .collect();
1907 if let Some(content_capture_ix) = content_capture_ix {
1908 self.grammar_mut()?.injection_config = Some(InjectionConfig {
1909 query,
1910 language_capture_ix,
1911 content_capture_ix,
1912 patterns,
1913 });
1914 } else {
1915 log::error!(
1916 "missing required capture in injections {} TreeSitter query: \
1917 content or injection.content",
1918 &self.config.name,
1919 );
1920 }
1921 }
1922 Ok(self)
1923 }
1924
1925 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1926 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1927
1928 let mut override_configs_by_id = HashMap::default();
1929 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1930 let mut range_is_inclusive = false;
1931 if name.starts_with('_') {
1932 continue;
1933 }
1934 if let Some(prefix) = name.strip_suffix(".inclusive") {
1935 name = prefix;
1936 range_is_inclusive = true;
1937 }
1938
1939 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1940 for server_name in &value.opt_into_language_servers {
1941 if !self
1942 .config
1943 .scope_opt_in_language_servers
1944 .contains(server_name)
1945 {
1946 util::debug_panic!(
1947 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1948 );
1949 }
1950 }
1951
1952 override_configs_by_id.insert(
1953 ix as u32,
1954 OverrideEntry {
1955 name: name.to_string(),
1956 range_is_inclusive,
1957 value,
1958 },
1959 );
1960 }
1961
1962 let referenced_override_names = self.config.overrides.keys().chain(
1963 self.config
1964 .brackets
1965 .disabled_scopes_by_bracket_ix
1966 .iter()
1967 .flatten(),
1968 );
1969
1970 for referenced_name in referenced_override_names {
1971 if !override_configs_by_id
1972 .values()
1973 .any(|entry| entry.name == *referenced_name)
1974 {
1975 anyhow::bail!(
1976 "language {:?} has overrides in config not in query: {referenced_name:?}",
1977 self.config.name
1978 );
1979 }
1980 }
1981
1982 for entry in override_configs_by_id.values_mut() {
1983 entry.value.disabled_bracket_ixs = self
1984 .config
1985 .brackets
1986 .disabled_scopes_by_bracket_ix
1987 .iter()
1988 .enumerate()
1989 .filter_map(|(ix, disabled_scope_names)| {
1990 if disabled_scope_names.contains(&entry.name) {
1991 Some(ix as u16)
1992 } else {
1993 None
1994 }
1995 })
1996 .collect();
1997 }
1998
1999 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
2000
2001 let grammar = self.grammar_mut()?;
2002 grammar.override_config = Some(OverrideConfig {
2003 query,
2004 values: override_configs_by_id,
2005 });
2006 Ok(self)
2007 }
2008
2009 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
2010 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
2011 let mut redaction_capture_ix = 0;
2012 if populate_capture_indices(
2013 &query,
2014 &self.config.name,
2015 "redactions",
2016 &[],
2017 &mut [Capture::Required("redact", &mut redaction_capture_ix)],
2018 ) {
2019 self.grammar_mut()?.redactions_config = Some(RedactionConfig {
2020 query,
2021 redaction_capture_ix,
2022 });
2023 }
2024 Ok(self)
2025 }
2026
2027 fn expect_grammar(&self) -> Result<&Grammar> {
2028 self.grammar
2029 .as_ref()
2030 .map(|grammar| grammar.as_ref())
2031 .context("no grammar for language")
2032 }
2033
2034 fn grammar_mut(&mut self) -> Result<&mut Grammar> {
2035 Arc::get_mut(self.grammar.as_mut().context("no grammar for language")?)
2036 .context("cannot mutate grammar")
2037 }
2038
2039 pub fn name(&self) -> LanguageName {
2040 self.config.name.clone()
2041 }
2042 pub fn manifest(&self) -> Option<&ManifestName> {
2043 self.manifest_name.as_ref()
2044 }
2045
2046 pub fn code_fence_block_name(&self) -> Arc<str> {
2047 self.config
2048 .code_fence_block_name
2049 .clone()
2050 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
2051 }
2052
2053 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
2054 self.context_provider.clone()
2055 }
2056
2057 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
2058 self.toolchain.clone()
2059 }
2060
2061 pub fn highlight_text<'a>(
2062 self: &'a Arc<Self>,
2063 text: &'a Rope,
2064 range: Range<usize>,
2065 ) -> Vec<(Range<usize>, HighlightId)> {
2066 let mut result = Vec::new();
2067 if let Some(grammar) = &self.grammar {
2068 let tree = grammar.parse_text(text, None);
2069 let captures =
2070 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
2071 grammar
2072 .highlights_config
2073 .as_ref()
2074 .map(|config| &config.query)
2075 });
2076 let highlight_maps = vec![grammar.highlight_map()];
2077 let mut offset = 0;
2078 for chunk in
2079 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
2080 {
2081 let end_offset = offset + chunk.text.len();
2082 if let Some(highlight_id) = chunk.syntax_highlight_id
2083 && !highlight_id.is_default()
2084 {
2085 result.push((offset..end_offset, highlight_id));
2086 }
2087 offset = end_offset;
2088 }
2089 }
2090 result
2091 }
2092
2093 pub fn path_suffixes(&self) -> &[String] {
2094 &self.config.matcher.path_suffixes
2095 }
2096
2097 pub fn should_autoclose_before(&self, c: char) -> bool {
2098 c.is_whitespace() || self.config.autoclose_before.contains(c)
2099 }
2100
2101 pub fn set_theme(&self, theme: &SyntaxTheme) {
2102 if let Some(grammar) = self.grammar.as_ref()
2103 && let Some(highlights_config) = &grammar.highlights_config
2104 {
2105 *grammar.highlight_map.lock() =
2106 HighlightMap::new(highlights_config.query.capture_names(), theme);
2107 }
2108 }
2109
2110 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
2111 self.grammar.as_ref()
2112 }
2113
2114 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
2115 LanguageScope {
2116 language: self.clone(),
2117 override_id: None,
2118 }
2119 }
2120
2121 pub fn lsp_id(&self) -> String {
2122 self.config.name.lsp_id()
2123 }
2124
2125 pub fn prettier_parser_name(&self) -> Option<&str> {
2126 self.config.prettier_parser_name.as_deref()
2127 }
2128
2129 pub fn config(&self) -> &LanguageConfig {
2130 &self.config
2131 }
2132}
2133
2134impl LanguageScope {
2135 pub fn path_suffixes(&self) -> &[String] {
2136 self.language.path_suffixes()
2137 }
2138
2139 pub fn language_name(&self) -> LanguageName {
2140 self.language.config.name.clone()
2141 }
2142
2143 pub fn collapsed_placeholder(&self) -> &str {
2144 self.language.config.collapsed_placeholder.as_ref()
2145 }
2146
2147 /// Returns line prefix that is inserted in e.g. line continuations or
2148 /// in `toggle comments` action.
2149 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
2150 Override::as_option(
2151 self.config_override().map(|o| &o.line_comments),
2152 Some(&self.language.config.line_comments),
2153 )
2154 .map_or([].as_slice(), |e| e.as_slice())
2155 }
2156
2157 /// Config for block comments for this language.
2158 pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
2159 Override::as_option(
2160 self.config_override().map(|o| &o.block_comment),
2161 self.language.config.block_comment.as_ref(),
2162 )
2163 }
2164
2165 /// Config for documentation-style block comments for this language.
2166 pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
2167 self.language.config.documentation_comment.as_ref()
2168 }
2169
2170 /// Returns list markers that are inserted unchanged on newline (e.g., `- `, `* `, `+ `).
2171 pub fn unordered_list(&self) -> &[Arc<str>] {
2172 &self.language.config.unordered_list
2173 }
2174
2175 /// Returns configuration for ordered lists with auto-incrementing numbers (e.g., `1. ` becomes `2. `).
2176 pub fn ordered_list(&self) -> &[OrderedListConfig] {
2177 &self.language.config.ordered_list
2178 }
2179
2180 /// Returns configuration for task list continuation, if any (e.g., `- [x] ` continues as `- [ ] `).
2181 pub fn task_list(&self) -> Option<&TaskListConfig> {
2182 self.language.config.task_list.as_ref()
2183 }
2184
2185 /// Returns additional regex patterns that act as prefix markers for creating
2186 /// boundaries during rewrapping.
2187 ///
2188 /// By default, Zed treats as paragraph and comment prefixes as boundaries.
2189 pub fn rewrap_prefixes(&self) -> &[Regex] {
2190 &self.language.config.rewrap_prefixes
2191 }
2192
2193 /// Returns a list of language-specific word characters.
2194 ///
2195 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
2196 /// the purpose of actions like 'move to next word end` or whole-word search.
2197 /// It additionally accounts for language's additional word characters.
2198 pub fn word_characters(&self) -> Option<&HashSet<char>> {
2199 Override::as_option(
2200 self.config_override().map(|o| &o.word_characters),
2201 Some(&self.language.config.word_characters),
2202 )
2203 }
2204
2205 /// Returns a list of language-specific characters that are considered part of
2206 /// a completion query.
2207 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
2208 Override::as_option(
2209 self.config_override()
2210 .map(|o| &o.completion_query_characters),
2211 Some(&self.language.config.completion_query_characters),
2212 )
2213 }
2214
2215 /// Returns a list of language-specific characters that are considered part of
2216 /// identifiers during linked editing operations.
2217 pub fn linked_edit_characters(&self) -> Option<&HashSet<char>> {
2218 Override::as_option(
2219 self.config_override().map(|o| &o.linked_edit_characters),
2220 Some(&self.language.config.linked_edit_characters),
2221 )
2222 }
2223
2224 /// Returns whether to prefer snippet `label` over `new_text` to replace text when
2225 /// completion is accepted.
2226 ///
2227 /// In cases like when cursor is in string or renaming existing function,
2228 /// you don't want to expand function signature instead just want function name
2229 /// to replace existing one.
2230 pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
2231 self.config_override()
2232 .and_then(|o| o.prefer_label_for_snippet)
2233 .unwrap_or(false)
2234 }
2235
2236 /// Returns a list of bracket pairs for a given language with an additional
2237 /// piece of information about whether the particular bracket pair is currently active for a given language.
2238 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
2239 let mut disabled_ids = self
2240 .config_override()
2241 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
2242 self.language
2243 .config
2244 .brackets
2245 .pairs
2246 .iter()
2247 .enumerate()
2248 .map(move |(ix, bracket)| {
2249 let mut is_enabled = true;
2250 if let Some(next_disabled_ix) = disabled_ids.first()
2251 && ix == *next_disabled_ix as usize
2252 {
2253 disabled_ids = &disabled_ids[1..];
2254 is_enabled = false;
2255 }
2256 (bracket, is_enabled)
2257 })
2258 }
2259
2260 pub fn should_autoclose_before(&self, c: char) -> bool {
2261 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
2262 }
2263
2264 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
2265 let config = &self.language.config;
2266 let opt_in_servers = &config.scope_opt_in_language_servers;
2267 if opt_in_servers.contains(name) {
2268 if let Some(over) = self.config_override() {
2269 over.opt_into_language_servers.contains(name)
2270 } else {
2271 false
2272 }
2273 } else {
2274 true
2275 }
2276 }
2277
2278 pub fn override_name(&self) -> Option<&str> {
2279 let id = self.override_id?;
2280 let grammar = self.language.grammar.as_ref()?;
2281 let override_config = grammar.override_config.as_ref()?;
2282 override_config.values.get(&id).map(|e| e.name.as_str())
2283 }
2284
2285 fn config_override(&self) -> Option<&LanguageConfigOverride> {
2286 let id = self.override_id?;
2287 let grammar = self.language.grammar.as_ref()?;
2288 let override_config = grammar.override_config.as_ref()?;
2289 override_config.values.get(&id).map(|e| &e.value)
2290 }
2291}
2292
2293impl Hash for Language {
2294 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2295 self.id.hash(state)
2296 }
2297}
2298
2299impl PartialEq for Language {
2300 fn eq(&self, other: &Self) -> bool {
2301 self.id.eq(&other.id)
2302 }
2303}
2304
2305impl Eq for Language {}
2306
2307impl Debug for Language {
2308 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2309 f.debug_struct("Language")
2310 .field("name", &self.config.name)
2311 .finish()
2312 }
2313}
2314
2315impl Grammar {
2316 pub fn id(&self) -> GrammarId {
2317 self.id
2318 }
2319
2320 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
2321 with_parser(|parser| {
2322 parser
2323 .set_language(&self.ts_language)
2324 .expect("incompatible grammar");
2325 let mut chunks = text.chunks_in_range(0..text.len());
2326 parser
2327 .parse_with_options(
2328 &mut move |offset, _| {
2329 chunks.seek(offset);
2330 chunks.next().unwrap_or("").as_bytes()
2331 },
2332 old_tree.as_ref(),
2333 None,
2334 )
2335 .unwrap()
2336 })
2337 }
2338
2339 pub fn highlight_map(&self) -> HighlightMap {
2340 self.highlight_map.lock().clone()
2341 }
2342
2343 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
2344 let capture_id = self
2345 .highlights_config
2346 .as_ref()?
2347 .query
2348 .capture_index_for_name(name)?;
2349 Some(self.highlight_map.lock().get(capture_id))
2350 }
2351
2352 pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2353 self.debug_variables_config.as_ref()
2354 }
2355
2356 pub fn imports_config(&self) -> Option<&ImportsConfig> {
2357 self.imports_config.as_ref()
2358 }
2359}
2360
2361impl CodeLabelBuilder {
2362 pub fn respan_filter_range(&mut self, filter_text: Option<&str>) {
2363 self.filter_range = filter_text
2364 .and_then(|filter| self.text.find(filter).map(|ix| ix..ix + filter.len()))
2365 .unwrap_or(0..self.text.len());
2366 }
2367
2368 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2369 let start_ix = self.text.len();
2370 self.text.push_str(text);
2371 if let Some(highlight) = highlight {
2372 let end_ix = self.text.len();
2373 self.runs.push((start_ix..end_ix, highlight));
2374 }
2375 }
2376
2377 pub fn build(mut self) -> CodeLabel {
2378 if self.filter_range.end == 0 {
2379 self.respan_filter_range(None);
2380 }
2381 CodeLabel {
2382 text: self.text,
2383 runs: self.runs,
2384 filter_range: self.filter_range,
2385 }
2386 }
2387}
2388
2389impl CodeLabel {
2390 pub fn fallback_for_completion(
2391 item: &lsp::CompletionItem,
2392 language: Option<&Language>,
2393 ) -> Self {
2394 let highlight_id = item.kind.and_then(|kind| {
2395 let grammar = language?.grammar()?;
2396 use lsp::CompletionItemKind as Kind;
2397 match kind {
2398 Kind::CLASS => grammar.highlight_id_for_name("type"),
2399 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2400 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2401 Kind::ENUM => grammar
2402 .highlight_id_for_name("enum")
2403 .or_else(|| grammar.highlight_id_for_name("type")),
2404 Kind::ENUM_MEMBER => grammar
2405 .highlight_id_for_name("variant")
2406 .or_else(|| grammar.highlight_id_for_name("property")),
2407 Kind::FIELD => grammar.highlight_id_for_name("property"),
2408 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2409 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2410 Kind::METHOD => grammar
2411 .highlight_id_for_name("function.method")
2412 .or_else(|| grammar.highlight_id_for_name("function")),
2413 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2414 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2415 Kind::STRUCT => grammar.highlight_id_for_name("type"),
2416 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2417 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2418 _ => None,
2419 }
2420 });
2421
2422 let label = &item.label;
2423 let label_length = label.len();
2424 let runs = highlight_id
2425 .map(|highlight_id| vec![(0..label_length, highlight_id)])
2426 .unwrap_or_default();
2427 let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2428 format!("{label} {detail}")
2429 } else if let Some(description) = item
2430 .label_details
2431 .as_ref()
2432 .and_then(|label_details| label_details.description.as_deref())
2433 .filter(|description| description != label)
2434 {
2435 format!("{label} {description}")
2436 } else {
2437 label.clone()
2438 };
2439 let filter_range = item
2440 .filter_text
2441 .as_deref()
2442 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2443 .unwrap_or(0..label_length);
2444 Self {
2445 text,
2446 runs,
2447 filter_range,
2448 }
2449 }
2450
2451 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2452 Self::filtered(text.clone(), text.len(), filter_text, Vec::new())
2453 }
2454
2455 pub fn filtered(
2456 text: String,
2457 label_len: usize,
2458 filter_text: Option<&str>,
2459 runs: Vec<(Range<usize>, HighlightId)>,
2460 ) -> Self {
2461 assert!(label_len <= text.len());
2462 let filter_range = filter_text
2463 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2464 .unwrap_or(0..label_len);
2465 Self::new(text, filter_range, runs)
2466 }
2467
2468 pub fn new(
2469 text: String,
2470 filter_range: Range<usize>,
2471 runs: Vec<(Range<usize>, HighlightId)>,
2472 ) -> Self {
2473 assert!(
2474 text.get(filter_range.clone()).is_some(),
2475 "invalid filter range"
2476 );
2477 runs.iter().for_each(|(range, _)| {
2478 assert!(
2479 text.get(range.clone()).is_some(),
2480 "invalid run range with inputs. Requested range {range:?} in text '{text}'",
2481 );
2482 });
2483 Self {
2484 runs,
2485 filter_range,
2486 text,
2487 }
2488 }
2489
2490 pub fn text(&self) -> &str {
2491 self.text.as_str()
2492 }
2493
2494 pub fn filter_text(&self) -> &str {
2495 &self.text[self.filter_range.clone()]
2496 }
2497}
2498
2499impl From<String> for CodeLabel {
2500 fn from(value: String) -> Self {
2501 Self::plain(value, None)
2502 }
2503}
2504
2505impl From<&str> for CodeLabel {
2506 fn from(value: &str) -> Self {
2507 Self::plain(value.to_string(), None)
2508 }
2509}
2510
2511impl Ord for LanguageMatcher {
2512 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2513 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2514 self.first_line_pattern
2515 .as_ref()
2516 .map(Regex::as_str)
2517 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2518 })
2519 }
2520}
2521
2522impl PartialOrd for LanguageMatcher {
2523 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2524 Some(self.cmp(other))
2525 }
2526}
2527
2528impl Eq for LanguageMatcher {}
2529
2530impl PartialEq for LanguageMatcher {
2531 fn eq(&self, other: &Self) -> bool {
2532 self.path_suffixes == other.path_suffixes
2533 && self.first_line_pattern.as_ref().map(Regex::as_str)
2534 == other.first_line_pattern.as_ref().map(Regex::as_str)
2535 }
2536}
2537
2538#[cfg(any(test, feature = "test-support"))]
2539impl Default for FakeLspAdapter {
2540 fn default() -> Self {
2541 Self {
2542 name: "the-fake-language-server",
2543 capabilities: lsp::LanguageServer::full_capabilities(),
2544 initializer: None,
2545 disk_based_diagnostics_progress_token: None,
2546 initialization_options: None,
2547 disk_based_diagnostics_sources: Vec::new(),
2548 prettier_plugins: Vec::new(),
2549 language_server_binary: LanguageServerBinary {
2550 path: "/the/fake/lsp/path".into(),
2551 arguments: vec![],
2552 env: Default::default(),
2553 },
2554 label_for_completion: None,
2555 }
2556 }
2557}
2558
2559#[cfg(any(test, feature = "test-support"))]
2560impl LspInstaller for FakeLspAdapter {
2561 type BinaryVersion = ();
2562
2563 async fn fetch_latest_server_version(
2564 &self,
2565 _: &dyn LspAdapterDelegate,
2566 _: bool,
2567 _: &mut AsyncApp,
2568 ) -> Result<Self::BinaryVersion> {
2569 unreachable!()
2570 }
2571
2572 async fn check_if_user_installed(
2573 &self,
2574 _: &dyn LspAdapterDelegate,
2575 _: Option<Toolchain>,
2576 _: &AsyncApp,
2577 ) -> Option<LanguageServerBinary> {
2578 Some(self.language_server_binary.clone())
2579 }
2580
2581 async fn fetch_server_binary(
2582 &self,
2583 _: (),
2584 _: PathBuf,
2585 _: &dyn LspAdapterDelegate,
2586 ) -> Result<LanguageServerBinary> {
2587 unreachable!();
2588 }
2589
2590 async fn cached_server_binary(
2591 &self,
2592 _: PathBuf,
2593 _: &dyn LspAdapterDelegate,
2594 ) -> Option<LanguageServerBinary> {
2595 unreachable!();
2596 }
2597}
2598
2599#[cfg(any(test, feature = "test-support"))]
2600#[async_trait(?Send)]
2601impl LspAdapter for FakeLspAdapter {
2602 fn name(&self) -> LanguageServerName {
2603 LanguageServerName(self.name.into())
2604 }
2605
2606 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2607 self.disk_based_diagnostics_sources.clone()
2608 }
2609
2610 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2611 self.disk_based_diagnostics_progress_token.clone()
2612 }
2613
2614 async fn initialization_options(
2615 self: Arc<Self>,
2616 _: &Arc<dyn LspAdapterDelegate>,
2617 ) -> Result<Option<Value>> {
2618 Ok(self.initialization_options.clone())
2619 }
2620
2621 async fn label_for_completion(
2622 &self,
2623 item: &lsp::CompletionItem,
2624 language: &Arc<Language>,
2625 ) -> Option<CodeLabel> {
2626 let label_for_completion = self.label_for_completion.as_ref()?;
2627 label_for_completion(item, language)
2628 }
2629
2630 fn is_extension(&self) -> bool {
2631 false
2632 }
2633}
2634
2635enum Capture<'a> {
2636 Required(&'static str, &'a mut u32),
2637 Optional(&'static str, &'a mut Option<u32>),
2638}
2639
2640fn populate_capture_indices(
2641 query: &Query,
2642 language_name: &LanguageName,
2643 query_type: &str,
2644 expected_prefixes: &[&str],
2645 captures: &mut [Capture<'_>],
2646) -> bool {
2647 let mut found_required_indices = Vec::new();
2648 'outer: for (ix, name) in query.capture_names().iter().enumerate() {
2649 for (required_ix, capture) in captures.iter_mut().enumerate() {
2650 match capture {
2651 Capture::Required(capture_name, index) if capture_name == name => {
2652 **index = ix as u32;
2653 found_required_indices.push(required_ix);
2654 continue 'outer;
2655 }
2656 Capture::Optional(capture_name, index) if capture_name == name => {
2657 **index = Some(ix as u32);
2658 continue 'outer;
2659 }
2660 _ => {}
2661 }
2662 }
2663 if !name.starts_with("_")
2664 && !expected_prefixes
2665 .iter()
2666 .any(|&prefix| name.starts_with(prefix))
2667 {
2668 log::warn!(
2669 "unrecognized capture name '{}' in {} {} TreeSitter query \
2670 (suppress this warning by prefixing with '_')",
2671 name,
2672 language_name,
2673 query_type
2674 );
2675 }
2676 }
2677 let mut missing_required_captures = Vec::new();
2678 for (capture_ix, capture) in captures.iter().enumerate() {
2679 if let Capture::Required(capture_name, _) = capture
2680 && !found_required_indices.contains(&capture_ix)
2681 {
2682 missing_required_captures.push(*capture_name);
2683 }
2684 }
2685 let success = missing_required_captures.is_empty();
2686 if !success {
2687 log::error!(
2688 "missing required capture(s) in {} {} TreeSitter query: {}",
2689 language_name,
2690 query_type,
2691 missing_required_captures.join(", ")
2692 );
2693 }
2694 success
2695}
2696
2697pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2698 lsp::Position::new(point.row, point.column)
2699}
2700
2701pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2702 Unclipped(PointUtf16::new(point.line, point.character))
2703}
2704
2705pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2706 anyhow::ensure!(
2707 range.start <= range.end,
2708 "Inverted range provided to an LSP request: {:?}-{:?}",
2709 range.start,
2710 range.end
2711 );
2712 Ok(lsp::Range {
2713 start: point_to_lsp(range.start),
2714 end: point_to_lsp(range.end),
2715 })
2716}
2717
2718pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2719 let mut start = point_from_lsp(range.start);
2720 let mut end = point_from_lsp(range.end);
2721 if start > end {
2722 // We debug instead of warn so that this is not logged by default unless explicitly requested.
2723 // Using warn would write to the log file, and since we receive an enormous amount of
2724 // range_from_lsp calls (especially during completions), that can hang the main thread.
2725 //
2726 // See issue #36223.
2727 zlog::debug!("range_from_lsp called with inverted range {start:?}-{end:?}");
2728 mem::swap(&mut start, &mut end);
2729 }
2730 start..end
2731}
2732
2733#[doc(hidden)]
2734#[cfg(any(test, feature = "test-support"))]
2735pub fn rust_lang() -> Arc<Language> {
2736 use std::borrow::Cow;
2737
2738 let language = Language::new(
2739 LanguageConfig {
2740 name: "Rust".into(),
2741 matcher: LanguageMatcher {
2742 path_suffixes: vec!["rs".to_string()],
2743 ..Default::default()
2744 },
2745 line_comments: vec!["// ".into(), "/// ".into(), "//! ".into()],
2746 ..Default::default()
2747 },
2748 Some(tree_sitter_rust::LANGUAGE.into()),
2749 )
2750 .with_queries(LanguageQueries {
2751 outline: Some(Cow::from(include_str!(
2752 "../../languages/src/rust/outline.scm"
2753 ))),
2754 indents: Some(Cow::from(include_str!(
2755 "../../languages/src/rust/indents.scm"
2756 ))),
2757 brackets: Some(Cow::from(include_str!(
2758 "../../languages/src/rust/brackets.scm"
2759 ))),
2760 text_objects: Some(Cow::from(include_str!(
2761 "../../languages/src/rust/textobjects.scm"
2762 ))),
2763 highlights: Some(Cow::from(include_str!(
2764 "../../languages/src/rust/highlights.scm"
2765 ))),
2766 injections: Some(Cow::from(include_str!(
2767 "../../languages/src/rust/injections.scm"
2768 ))),
2769 overrides: Some(Cow::from(include_str!(
2770 "../../languages/src/rust/overrides.scm"
2771 ))),
2772 redactions: None,
2773 runnables: Some(Cow::from(include_str!(
2774 "../../languages/src/rust/runnables.scm"
2775 ))),
2776 debugger: Some(Cow::from(include_str!(
2777 "../../languages/src/rust/debugger.scm"
2778 ))),
2779 imports: Some(Cow::from(include_str!(
2780 "../../languages/src/rust/imports.scm"
2781 ))),
2782 })
2783 .expect("Could not parse queries");
2784 Arc::new(language)
2785}
2786
2787#[doc(hidden)]
2788#[cfg(any(test, feature = "test-support"))]
2789pub fn markdown_lang() -> Arc<Language> {
2790 use std::borrow::Cow;
2791
2792 let language = Language::new(
2793 LanguageConfig {
2794 name: "Markdown".into(),
2795 matcher: LanguageMatcher {
2796 path_suffixes: vec!["md".into()],
2797 ..Default::default()
2798 },
2799 ..LanguageConfig::default()
2800 },
2801 Some(tree_sitter_md::LANGUAGE.into()),
2802 )
2803 .with_queries(LanguageQueries {
2804 brackets: Some(Cow::from(include_str!(
2805 "../../languages/src/markdown/brackets.scm"
2806 ))),
2807 injections: Some(Cow::from(include_str!(
2808 "../../languages/src/markdown/injections.scm"
2809 ))),
2810 highlights: Some(Cow::from(include_str!(
2811 "../../languages/src/markdown/highlights.scm"
2812 ))),
2813 indents: Some(Cow::from(include_str!(
2814 "../../languages/src/markdown/indents.scm"
2815 ))),
2816 outline: Some(Cow::from(include_str!(
2817 "../../languages/src/markdown/outline.scm"
2818 ))),
2819 ..LanguageQueries::default()
2820 })
2821 .expect("Could not parse markdown queries");
2822 Arc::new(language)
2823}
2824
2825#[cfg(test)]
2826mod tests {
2827 use super::*;
2828 use gpui::TestAppContext;
2829 use pretty_assertions::assert_matches;
2830
2831 #[gpui::test(iterations = 10)]
2832 async fn test_language_loading(cx: &mut TestAppContext) {
2833 let languages = LanguageRegistry::test(cx.executor());
2834 let languages = Arc::new(languages);
2835 languages.register_native_grammars([
2836 ("json", tree_sitter_json::LANGUAGE),
2837 ("rust", tree_sitter_rust::LANGUAGE),
2838 ]);
2839 languages.register_test_language(LanguageConfig {
2840 name: "JSON".into(),
2841 grammar: Some("json".into()),
2842 matcher: LanguageMatcher {
2843 path_suffixes: vec!["json".into()],
2844 ..Default::default()
2845 },
2846 ..Default::default()
2847 });
2848 languages.register_test_language(LanguageConfig {
2849 name: "Rust".into(),
2850 grammar: Some("rust".into()),
2851 matcher: LanguageMatcher {
2852 path_suffixes: vec!["rs".into()],
2853 ..Default::default()
2854 },
2855 ..Default::default()
2856 });
2857 assert_eq!(
2858 languages.language_names(),
2859 &[
2860 LanguageName::new_static("JSON"),
2861 LanguageName::new_static("Plain Text"),
2862 LanguageName::new_static("Rust"),
2863 ]
2864 );
2865
2866 let rust1 = languages.language_for_name("Rust");
2867 let rust2 = languages.language_for_name("Rust");
2868
2869 // Ensure language is still listed even if it's being loaded.
2870 assert_eq!(
2871 languages.language_names(),
2872 &[
2873 LanguageName::new_static("JSON"),
2874 LanguageName::new_static("Plain Text"),
2875 LanguageName::new_static("Rust"),
2876 ]
2877 );
2878
2879 let (rust1, rust2) = futures::join!(rust1, rust2);
2880 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2881
2882 // Ensure language is still listed even after loading it.
2883 assert_eq!(
2884 languages.language_names(),
2885 &[
2886 LanguageName::new_static("JSON"),
2887 LanguageName::new_static("Plain Text"),
2888 LanguageName::new_static("Rust"),
2889 ]
2890 );
2891
2892 // Loading an unknown language returns an error.
2893 assert!(languages.language_for_name("Unknown").await.is_err());
2894 }
2895
2896 #[gpui::test]
2897 async fn test_completion_label_omits_duplicate_data() {
2898 let regular_completion_item_1 = lsp::CompletionItem {
2899 label: "regular1".to_string(),
2900 detail: Some("detail1".to_string()),
2901 label_details: Some(lsp::CompletionItemLabelDetails {
2902 detail: None,
2903 description: Some("description 1".to_string()),
2904 }),
2905 ..lsp::CompletionItem::default()
2906 };
2907
2908 let regular_completion_item_2 = lsp::CompletionItem {
2909 label: "regular2".to_string(),
2910 label_details: Some(lsp::CompletionItemLabelDetails {
2911 detail: None,
2912 description: Some("description 2".to_string()),
2913 }),
2914 ..lsp::CompletionItem::default()
2915 };
2916
2917 let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2918 detail: Some(regular_completion_item_1.label.clone()),
2919 ..regular_completion_item_1.clone()
2920 };
2921
2922 let completion_item_with_duplicate_detail = lsp::CompletionItem {
2923 detail: Some(regular_completion_item_1.label.clone()),
2924 label_details: None,
2925 ..regular_completion_item_1.clone()
2926 };
2927
2928 let completion_item_with_duplicate_description = lsp::CompletionItem {
2929 label_details: Some(lsp::CompletionItemLabelDetails {
2930 detail: None,
2931 description: Some(regular_completion_item_2.label.clone()),
2932 }),
2933 ..regular_completion_item_2.clone()
2934 };
2935
2936 assert_eq!(
2937 CodeLabel::fallback_for_completion(®ular_completion_item_1, None).text,
2938 format!(
2939 "{} {}",
2940 regular_completion_item_1.label,
2941 regular_completion_item_1.detail.unwrap()
2942 ),
2943 "LSP completion items with both detail and label_details.description should prefer detail"
2944 );
2945 assert_eq!(
2946 CodeLabel::fallback_for_completion(®ular_completion_item_2, None).text,
2947 format!(
2948 "{} {}",
2949 regular_completion_item_2.label,
2950 regular_completion_item_2
2951 .label_details
2952 .as_ref()
2953 .unwrap()
2954 .description
2955 .as_ref()
2956 .unwrap()
2957 ),
2958 "LSP completion items without detail but with label_details.description should use that"
2959 );
2960 assert_eq!(
2961 CodeLabel::fallback_for_completion(
2962 &completion_item_with_duplicate_detail_and_proper_description,
2963 None
2964 )
2965 .text,
2966 format!(
2967 "{} {}",
2968 regular_completion_item_1.label,
2969 regular_completion_item_1
2970 .label_details
2971 .as_ref()
2972 .unwrap()
2973 .description
2974 .as_ref()
2975 .unwrap()
2976 ),
2977 "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2978 );
2979 assert_eq!(
2980 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2981 regular_completion_item_1.label,
2982 "LSP completion items with duplicate label and detail, should omit the detail"
2983 );
2984 assert_eq!(
2985 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2986 .text,
2987 regular_completion_item_2.label,
2988 "LSP completion items with duplicate label and detail, should omit the detail"
2989 );
2990 }
2991
2992 #[test]
2993 fn test_deserializing_comments_backwards_compat() {
2994 // current version of `block_comment` and `documentation_comment` work
2995 {
2996 let config: LanguageConfig = ::toml::from_str(
2997 r#"
2998 name = "Foo"
2999 block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
3000 documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
3001 "#,
3002 )
3003 .unwrap();
3004 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
3005 assert_matches!(
3006 config.documentation_comment,
3007 Some(BlockCommentConfig { .. })
3008 );
3009
3010 let block_config = config.block_comment.unwrap();
3011 assert_eq!(block_config.start.as_ref(), "a");
3012 assert_eq!(block_config.end.as_ref(), "b");
3013 assert_eq!(block_config.prefix.as_ref(), "c");
3014 assert_eq!(block_config.tab_size, 1);
3015
3016 let doc_config = config.documentation_comment.unwrap();
3017 assert_eq!(doc_config.start.as_ref(), "d");
3018 assert_eq!(doc_config.end.as_ref(), "e");
3019 assert_eq!(doc_config.prefix.as_ref(), "f");
3020 assert_eq!(doc_config.tab_size, 2);
3021 }
3022
3023 // former `documentation` setting is read into `documentation_comment`
3024 {
3025 let config: LanguageConfig = ::toml::from_str(
3026 r#"
3027 name = "Foo"
3028 documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
3029 "#,
3030 )
3031 .unwrap();
3032 assert_matches!(
3033 config.documentation_comment,
3034 Some(BlockCommentConfig { .. })
3035 );
3036
3037 let config = config.documentation_comment.unwrap();
3038 assert_eq!(config.start.as_ref(), "a");
3039 assert_eq!(config.end.as_ref(), "b");
3040 assert_eq!(config.prefix.as_ref(), "c");
3041 assert_eq!(config.tab_size, 1);
3042 }
3043
3044 // old block_comment format is read into BlockCommentConfig
3045 {
3046 let config: LanguageConfig = ::toml::from_str(
3047 r#"
3048 name = "Foo"
3049 block_comment = ["a", "b"]
3050 "#,
3051 )
3052 .unwrap();
3053 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
3054
3055 let config = config.block_comment.unwrap();
3056 assert_eq!(config.start.as_ref(), "a");
3057 assert_eq!(config.end.as_ref(), "b");
3058 assert_eq!(config.prefix.as_ref(), "");
3059 assert_eq!(config.tab_size, 0);
3060 }
3061 }
3062}