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