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