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