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