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}
1326
1327pub struct DebugVariablesConfig {
1328 pub query: Query,
1329 pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1330}
1331
1332pub struct ImportsConfig {
1333 pub query: Query,
1334 pub import_ix: u32,
1335 pub name_ix: Option<u32>,
1336 pub namespace_ix: Option<u32>,
1337 pub source_ix: Option<u32>,
1338 pub list_ix: Option<u32>,
1339 pub wildcard_ix: Option<u32>,
1340 pub alias_ix: Option<u32>,
1341}
1342
1343impl Language {
1344 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1345 Self::new_with_id(LanguageId::new(), config, ts_language)
1346 }
1347
1348 pub fn id(&self) -> LanguageId {
1349 self.id
1350 }
1351
1352 fn new_with_id(
1353 id: LanguageId,
1354 config: LanguageConfig,
1355 ts_language: Option<tree_sitter::Language>,
1356 ) -> Self {
1357 Self {
1358 id,
1359 config,
1360 grammar: ts_language.map(|ts_language| {
1361 Arc::new(Grammar {
1362 id: GrammarId::new(),
1363 highlights_config: None,
1364 brackets_config: None,
1365 outline_config: None,
1366 text_object_config: None,
1367 embedding_config: None,
1368 indents_config: None,
1369 injection_config: None,
1370 override_config: None,
1371 redactions_config: None,
1372 runnable_config: None,
1373 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1374 debug_variables_config: None,
1375 imports_config: None,
1376 ts_language,
1377 highlight_map: Default::default(),
1378 })
1379 }),
1380 context_provider: None,
1381 toolchain: None,
1382 manifest_name: None,
1383 }
1384 }
1385
1386 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1387 self.context_provider = provider;
1388 self
1389 }
1390
1391 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1392 self.toolchain = provider;
1393 self
1394 }
1395
1396 pub fn with_manifest(mut self, name: Option<ManifestName>) -> Self {
1397 self.manifest_name = name;
1398 self
1399 }
1400
1401 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1402 if let Some(query) = queries.highlights {
1403 self = self
1404 .with_highlights_query(query.as_ref())
1405 .context("Error loading highlights query")?;
1406 }
1407 if let Some(query) = queries.brackets {
1408 self = self
1409 .with_brackets_query(query.as_ref())
1410 .context("Error loading brackets query")?;
1411 }
1412 if let Some(query) = queries.indents {
1413 self = self
1414 .with_indents_query(query.as_ref())
1415 .context("Error loading indents query")?;
1416 }
1417 if let Some(query) = queries.outline {
1418 self = self
1419 .with_outline_query(query.as_ref())
1420 .context("Error loading outline query")?;
1421 }
1422 if let Some(query) = queries.embedding {
1423 self = self
1424 .with_embedding_query(query.as_ref())
1425 .context("Error loading embedding query")?;
1426 }
1427 if let Some(query) = queries.injections {
1428 self = self
1429 .with_injection_query(query.as_ref())
1430 .context("Error loading injection query")?;
1431 }
1432 if let Some(query) = queries.overrides {
1433 self = self
1434 .with_override_query(query.as_ref())
1435 .context("Error loading override query")?;
1436 }
1437 if let Some(query) = queries.redactions {
1438 self = self
1439 .with_redaction_query(query.as_ref())
1440 .context("Error loading redaction query")?;
1441 }
1442 if let Some(query) = queries.runnables {
1443 self = self
1444 .with_runnable_query(query.as_ref())
1445 .context("Error loading runnables query")?;
1446 }
1447 if let Some(query) = queries.text_objects {
1448 self = self
1449 .with_text_object_query(query.as_ref())
1450 .context("Error loading textobject query")?;
1451 }
1452 if let Some(query) = queries.debugger {
1453 self = self
1454 .with_debug_variables_query(query.as_ref())
1455 .context("Error loading debug variables query")?;
1456 }
1457 if let Some(query) = queries.imports {
1458 self = self
1459 .with_imports_query(query.as_ref())
1460 .context("Error loading imports query")?;
1461 }
1462 Ok(self)
1463 }
1464
1465 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1466 let grammar = self.grammar_mut()?;
1467 let query = Query::new(&grammar.ts_language, source)?;
1468
1469 let mut identifier_capture_indices = Vec::new();
1470 for name in [
1471 "variable",
1472 "constant",
1473 "constructor",
1474 "function",
1475 "function.method",
1476 "function.method.call",
1477 "function.special",
1478 "property",
1479 "type",
1480 "type.interface",
1481 ] {
1482 identifier_capture_indices.extend(query.capture_index_for_name(name));
1483 }
1484
1485 grammar.highlights_config = Some(HighlightsConfig {
1486 query,
1487 identifier_capture_indices,
1488 });
1489
1490 Ok(self)
1491 }
1492
1493 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1494 let grammar = self.grammar_mut()?;
1495
1496 let query = Query::new(&grammar.ts_language, source)?;
1497 let extra_captures: Vec<_> = query
1498 .capture_names()
1499 .iter()
1500 .map(|&name| match name {
1501 "run" => RunnableCapture::Run,
1502 name => RunnableCapture::Named(name.to_string().into()),
1503 })
1504 .collect();
1505
1506 grammar.runnable_config = Some(RunnableConfig {
1507 extra_captures,
1508 query,
1509 });
1510
1511 Ok(self)
1512 }
1513
1514 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1515 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1516 let mut item_capture_ix = 0;
1517 let mut name_capture_ix = 0;
1518 let mut context_capture_ix = None;
1519 let mut extra_context_capture_ix = None;
1520 let mut open_capture_ix = None;
1521 let mut close_capture_ix = None;
1522 let mut annotation_capture_ix = None;
1523 if populate_capture_indices(
1524 &query,
1525 &self.config.name,
1526 "outline",
1527 &[],
1528 &mut [
1529 Capture::Required("item", &mut item_capture_ix),
1530 Capture::Required("name", &mut name_capture_ix),
1531 Capture::Optional("context", &mut context_capture_ix),
1532 Capture::Optional("context.extra", &mut extra_context_capture_ix),
1533 Capture::Optional("open", &mut open_capture_ix),
1534 Capture::Optional("close", &mut close_capture_ix),
1535 Capture::Optional("annotation", &mut annotation_capture_ix),
1536 ],
1537 ) {
1538 self.grammar_mut()?.outline_config = Some(OutlineConfig {
1539 query,
1540 item_capture_ix,
1541 name_capture_ix,
1542 context_capture_ix,
1543 extra_context_capture_ix,
1544 open_capture_ix,
1545 close_capture_ix,
1546 annotation_capture_ix,
1547 });
1548 }
1549 Ok(self)
1550 }
1551
1552 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1553 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1554
1555 let mut text_objects_by_capture_ix = Vec::new();
1556 for (ix, name) in query.capture_names().iter().enumerate() {
1557 if let Some(text_object) = TextObject::from_capture_name(name) {
1558 text_objects_by_capture_ix.push((ix as u32, text_object));
1559 } else {
1560 log::warn!(
1561 "unrecognized capture name '{}' in {} textobjects TreeSitter query",
1562 name,
1563 self.config.name,
1564 );
1565 }
1566 }
1567
1568 self.grammar_mut()?.text_object_config = Some(TextObjectConfig {
1569 query,
1570 text_objects_by_capture_ix,
1571 });
1572 Ok(self)
1573 }
1574
1575 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1576 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1577 let mut item_capture_ix = 0;
1578 let mut name_capture_ix = None;
1579 let mut context_capture_ix = None;
1580 let mut collapse_capture_ix = None;
1581 let mut keep_capture_ix = None;
1582 if populate_capture_indices(
1583 &query,
1584 &self.config.name,
1585 "embedding",
1586 &[],
1587 &mut [
1588 Capture::Required("item", &mut item_capture_ix),
1589 Capture::Optional("name", &mut name_capture_ix),
1590 Capture::Optional("context", &mut context_capture_ix),
1591 Capture::Optional("keep", &mut keep_capture_ix),
1592 Capture::Optional("collapse", &mut collapse_capture_ix),
1593 ],
1594 ) {
1595 self.grammar_mut()?.embedding_config = Some(EmbeddingConfig {
1596 query,
1597 item_capture_ix,
1598 name_capture_ix,
1599 context_capture_ix,
1600 collapse_capture_ix,
1601 keep_capture_ix,
1602 });
1603 }
1604 Ok(self)
1605 }
1606
1607 pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1608 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1609
1610 let mut objects_by_capture_ix = Vec::new();
1611 for (ix, name) in query.capture_names().iter().enumerate() {
1612 if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1613 objects_by_capture_ix.push((ix as u32, text_object));
1614 } else {
1615 log::warn!(
1616 "unrecognized capture name '{}' in {} debugger TreeSitter query",
1617 name,
1618 self.config.name,
1619 );
1620 }
1621 }
1622
1623 self.grammar_mut()?.debug_variables_config = Some(DebugVariablesConfig {
1624 query,
1625 objects_by_capture_ix,
1626 });
1627 Ok(self)
1628 }
1629
1630 pub fn with_imports_query(mut self, source: &str) -> Result<Self> {
1631 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1632
1633 let mut import_ix = 0;
1634 let mut name_ix = None;
1635 let mut namespace_ix = None;
1636 let mut source_ix = None;
1637 let mut list_ix = None;
1638 let mut wildcard_ix = None;
1639 let mut alias_ix = None;
1640 if populate_capture_indices(
1641 &query,
1642 &self.config.name,
1643 "imports",
1644 &[],
1645 &mut [
1646 Capture::Required("import", &mut import_ix),
1647 Capture::Optional("name", &mut name_ix),
1648 Capture::Optional("namespace", &mut namespace_ix),
1649 Capture::Optional("source", &mut source_ix),
1650 Capture::Optional("list", &mut list_ix),
1651 Capture::Optional("wildcard", &mut wildcard_ix),
1652 Capture::Optional("alias", &mut alias_ix),
1653 ],
1654 ) {
1655 self.grammar_mut()?.imports_config = Some(ImportsConfig {
1656 query,
1657 import_ix,
1658 name_ix,
1659 namespace_ix,
1660 source_ix,
1661 list_ix,
1662 wildcard_ix,
1663 alias_ix,
1664 });
1665 }
1666 return Ok(self);
1667 }
1668
1669 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1670 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1671 let mut open_capture_ix = 0;
1672 let mut close_capture_ix = 0;
1673 if populate_capture_indices(
1674 &query,
1675 &self.config.name,
1676 "brackets",
1677 &[],
1678 &mut [
1679 Capture::Required("open", &mut open_capture_ix),
1680 Capture::Required("close", &mut close_capture_ix),
1681 ],
1682 ) {
1683 let patterns = (0..query.pattern_count())
1684 .map(|ix| {
1685 let mut config = BracketsPatternConfig::default();
1686 for setting in query.property_settings(ix) {
1687 if setting.key.as_ref() == "newline.only" {
1688 config.newline_only = true
1689 }
1690 }
1691 config
1692 })
1693 .collect();
1694 self.grammar_mut()?.brackets_config = Some(BracketsConfig {
1695 query,
1696 open_capture_ix,
1697 close_capture_ix,
1698 patterns,
1699 });
1700 }
1701 Ok(self)
1702 }
1703
1704 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1705 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1706 let mut indent_capture_ix = 0;
1707 let mut start_capture_ix = None;
1708 let mut end_capture_ix = None;
1709 let mut outdent_capture_ix = None;
1710 if populate_capture_indices(
1711 &query,
1712 &self.config.name,
1713 "indents",
1714 &["start."],
1715 &mut [
1716 Capture::Required("indent", &mut indent_capture_ix),
1717 Capture::Optional("start", &mut start_capture_ix),
1718 Capture::Optional("end", &mut end_capture_ix),
1719 Capture::Optional("outdent", &mut outdent_capture_ix),
1720 ],
1721 ) {
1722 let mut suffixed_start_captures = HashMap::default();
1723 for (ix, name) in query.capture_names().iter().enumerate() {
1724 if let Some(suffix) = name.strip_prefix("start.") {
1725 suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1726 }
1727 }
1728
1729 self.grammar_mut()?.indents_config = Some(IndentConfig {
1730 query,
1731 indent_capture_ix,
1732 start_capture_ix,
1733 end_capture_ix,
1734 outdent_capture_ix,
1735 suffixed_start_captures,
1736 });
1737 }
1738 Ok(self)
1739 }
1740
1741 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1742 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1743 let mut language_capture_ix = None;
1744 let mut injection_language_capture_ix = None;
1745 let mut content_capture_ix = None;
1746 let mut injection_content_capture_ix = None;
1747 if populate_capture_indices(
1748 &query,
1749 &self.config.name,
1750 "injections",
1751 &[],
1752 &mut [
1753 Capture::Optional("language", &mut language_capture_ix),
1754 Capture::Optional("injection.language", &mut injection_language_capture_ix),
1755 Capture::Optional("content", &mut content_capture_ix),
1756 Capture::Optional("injection.content", &mut injection_content_capture_ix),
1757 ],
1758 ) {
1759 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1760 (None, Some(ix)) => Some(ix),
1761 (Some(_), Some(_)) => {
1762 anyhow::bail!("both language and injection.language captures are present");
1763 }
1764 _ => language_capture_ix,
1765 };
1766 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1767 (None, Some(ix)) => Some(ix),
1768 (Some(_), Some(_)) => {
1769 anyhow::bail!("both content and injection.content captures are present")
1770 }
1771 _ => content_capture_ix,
1772 };
1773 let patterns = (0..query.pattern_count())
1774 .map(|ix| {
1775 let mut config = InjectionPatternConfig::default();
1776 for setting in query.property_settings(ix) {
1777 match setting.key.as_ref() {
1778 "language" | "injection.language" => {
1779 config.language.clone_from(&setting.value);
1780 }
1781 "combined" | "injection.combined" => {
1782 config.combined = true;
1783 }
1784 _ => {}
1785 }
1786 }
1787 config
1788 })
1789 .collect();
1790 if let Some(content_capture_ix) = content_capture_ix {
1791 self.grammar_mut()?.injection_config = Some(InjectionConfig {
1792 query,
1793 language_capture_ix,
1794 content_capture_ix,
1795 patterns,
1796 });
1797 } else {
1798 log::error!(
1799 "missing required capture in injections {} TreeSitter query: \
1800 content or injection.content",
1801 &self.config.name,
1802 );
1803 }
1804 }
1805 Ok(self)
1806 }
1807
1808 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1809 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1810
1811 let mut override_configs_by_id = HashMap::default();
1812 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1813 let mut range_is_inclusive = false;
1814 if name.starts_with('_') {
1815 continue;
1816 }
1817 if let Some(prefix) = name.strip_suffix(".inclusive") {
1818 name = prefix;
1819 range_is_inclusive = true;
1820 }
1821
1822 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1823 for server_name in &value.opt_into_language_servers {
1824 if !self
1825 .config
1826 .scope_opt_in_language_servers
1827 .contains(server_name)
1828 {
1829 util::debug_panic!(
1830 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1831 );
1832 }
1833 }
1834
1835 override_configs_by_id.insert(
1836 ix as u32,
1837 OverrideEntry {
1838 name: name.to_string(),
1839 range_is_inclusive,
1840 value,
1841 },
1842 );
1843 }
1844
1845 let referenced_override_names = self.config.overrides.keys().chain(
1846 self.config
1847 .brackets
1848 .disabled_scopes_by_bracket_ix
1849 .iter()
1850 .flatten(),
1851 );
1852
1853 for referenced_name in referenced_override_names {
1854 if !override_configs_by_id
1855 .values()
1856 .any(|entry| entry.name == *referenced_name)
1857 {
1858 anyhow::bail!(
1859 "language {:?} has overrides in config not in query: {referenced_name:?}",
1860 self.config.name
1861 );
1862 }
1863 }
1864
1865 for entry in override_configs_by_id.values_mut() {
1866 entry.value.disabled_bracket_ixs = self
1867 .config
1868 .brackets
1869 .disabled_scopes_by_bracket_ix
1870 .iter()
1871 .enumerate()
1872 .filter_map(|(ix, disabled_scope_names)| {
1873 if disabled_scope_names.contains(&entry.name) {
1874 Some(ix as u16)
1875 } else {
1876 None
1877 }
1878 })
1879 .collect();
1880 }
1881
1882 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1883
1884 let grammar = self.grammar_mut()?;
1885 grammar.override_config = Some(OverrideConfig {
1886 query,
1887 values: override_configs_by_id,
1888 });
1889 Ok(self)
1890 }
1891
1892 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1893 let query = Query::new(&self.expect_grammar()?.ts_language, source)?;
1894 let mut redaction_capture_ix = 0;
1895 if populate_capture_indices(
1896 &query,
1897 &self.config.name,
1898 "redactions",
1899 &[],
1900 &mut [Capture::Required("redact", &mut redaction_capture_ix)],
1901 ) {
1902 self.grammar_mut()?.redactions_config = Some(RedactionConfig {
1903 query,
1904 redaction_capture_ix,
1905 });
1906 }
1907 Ok(self)
1908 }
1909
1910 fn expect_grammar(&self) -> Result<&Grammar> {
1911 self.grammar
1912 .as_ref()
1913 .map(|grammar| grammar.as_ref())
1914 .context("no grammar for language")
1915 }
1916
1917 fn grammar_mut(&mut self) -> Result<&mut Grammar> {
1918 Arc::get_mut(self.grammar.as_mut().context("no grammar for language")?)
1919 .context("cannot mutate grammar")
1920 }
1921
1922 pub fn name(&self) -> LanguageName {
1923 self.config.name.clone()
1924 }
1925 pub fn manifest(&self) -> Option<&ManifestName> {
1926 self.manifest_name.as_ref()
1927 }
1928
1929 pub fn code_fence_block_name(&self) -> Arc<str> {
1930 self.config
1931 .code_fence_block_name
1932 .clone()
1933 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1934 }
1935
1936 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1937 self.context_provider.clone()
1938 }
1939
1940 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1941 self.toolchain.clone()
1942 }
1943
1944 pub fn highlight_text<'a>(
1945 self: &'a Arc<Self>,
1946 text: &'a Rope,
1947 range: Range<usize>,
1948 ) -> Vec<(Range<usize>, HighlightId)> {
1949 let mut result = Vec::new();
1950 if let Some(grammar) = &self.grammar {
1951 let tree = grammar.parse_text(text, None);
1952 let captures =
1953 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1954 grammar
1955 .highlights_config
1956 .as_ref()
1957 .map(|config| &config.query)
1958 });
1959 let highlight_maps = vec![grammar.highlight_map()];
1960 let mut offset = 0;
1961 for chunk in
1962 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1963 {
1964 let end_offset = offset + chunk.text.len();
1965 if let Some(highlight_id) = chunk.syntax_highlight_id
1966 && !highlight_id.is_default()
1967 {
1968 result.push((offset..end_offset, highlight_id));
1969 }
1970 offset = end_offset;
1971 }
1972 }
1973 result
1974 }
1975
1976 pub fn path_suffixes(&self) -> &[String] {
1977 &self.config.matcher.path_suffixes
1978 }
1979
1980 pub fn should_autoclose_before(&self, c: char) -> bool {
1981 c.is_whitespace() || self.config.autoclose_before.contains(c)
1982 }
1983
1984 pub fn set_theme(&self, theme: &SyntaxTheme) {
1985 if let Some(grammar) = self.grammar.as_ref()
1986 && let Some(highlights_config) = &grammar.highlights_config
1987 {
1988 *grammar.highlight_map.lock() =
1989 HighlightMap::new(highlights_config.query.capture_names(), theme);
1990 }
1991 }
1992
1993 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1994 self.grammar.as_ref()
1995 }
1996
1997 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1998 LanguageScope {
1999 language: self.clone(),
2000 override_id: None,
2001 }
2002 }
2003
2004 pub fn lsp_id(&self) -> String {
2005 self.config.name.lsp_id()
2006 }
2007
2008 pub fn prettier_parser_name(&self) -> Option<&str> {
2009 self.config.prettier_parser_name.as_deref()
2010 }
2011
2012 pub fn config(&self) -> &LanguageConfig {
2013 &self.config
2014 }
2015}
2016
2017impl LanguageScope {
2018 pub fn path_suffixes(&self) -> &[String] {
2019 self.language.path_suffixes()
2020 }
2021
2022 pub fn language_name(&self) -> LanguageName {
2023 self.language.config.name.clone()
2024 }
2025
2026 pub fn collapsed_placeholder(&self) -> &str {
2027 self.language.config.collapsed_placeholder.as_ref()
2028 }
2029
2030 /// Returns line prefix that is inserted in e.g. line continuations or
2031 /// in `toggle comments` action.
2032 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
2033 Override::as_option(
2034 self.config_override().map(|o| &o.line_comments),
2035 Some(&self.language.config.line_comments),
2036 )
2037 .map_or([].as_slice(), |e| e.as_slice())
2038 }
2039
2040 /// Config for block comments for this language.
2041 pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
2042 Override::as_option(
2043 self.config_override().map(|o| &o.block_comment),
2044 self.language.config.block_comment.as_ref(),
2045 )
2046 }
2047
2048 /// Config for documentation-style block comments for this language.
2049 pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
2050 self.language.config.documentation_comment.as_ref()
2051 }
2052
2053 /// Returns additional regex patterns that act as prefix markers for creating
2054 /// boundaries during rewrapping.
2055 ///
2056 /// By default, Zed treats as paragraph and comment prefixes as boundaries.
2057 pub fn rewrap_prefixes(&self) -> &[Regex] {
2058 &self.language.config.rewrap_prefixes
2059 }
2060
2061 /// Returns a list of language-specific word characters.
2062 ///
2063 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
2064 /// the purpose of actions like 'move to next word end` or whole-word search.
2065 /// It additionally accounts for language's additional word characters.
2066 pub fn word_characters(&self) -> Option<&HashSet<char>> {
2067 Override::as_option(
2068 self.config_override().map(|o| &o.word_characters),
2069 Some(&self.language.config.word_characters),
2070 )
2071 }
2072
2073 /// Returns a list of language-specific characters that are considered part of
2074 /// a completion query.
2075 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
2076 Override::as_option(
2077 self.config_override()
2078 .map(|o| &o.completion_query_characters),
2079 Some(&self.language.config.completion_query_characters),
2080 )
2081 }
2082
2083 /// Returns a list of language-specific characters that are considered part of
2084 /// identifiers during linked editing operations.
2085 pub fn linked_edit_characters(&self) -> Option<&HashSet<char>> {
2086 Override::as_option(
2087 self.config_override().map(|o| &o.linked_edit_characters),
2088 Some(&self.language.config.linked_edit_characters),
2089 )
2090 }
2091
2092 /// Returns whether to prefer snippet `label` over `new_text` to replace text when
2093 /// completion is accepted.
2094 ///
2095 /// In cases like when cursor is in string or renaming existing function,
2096 /// you don't want to expand function signature instead just want function name
2097 /// to replace existing one.
2098 pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
2099 self.config_override()
2100 .and_then(|o| o.prefer_label_for_snippet)
2101 .unwrap_or(false)
2102 }
2103
2104 /// Returns a list of bracket pairs for a given language with an additional
2105 /// piece of information about whether the particular bracket pair is currently active for a given language.
2106 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
2107 let mut disabled_ids = self
2108 .config_override()
2109 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
2110 self.language
2111 .config
2112 .brackets
2113 .pairs
2114 .iter()
2115 .enumerate()
2116 .map(move |(ix, bracket)| {
2117 let mut is_enabled = true;
2118 if let Some(next_disabled_ix) = disabled_ids.first()
2119 && ix == *next_disabled_ix as usize
2120 {
2121 disabled_ids = &disabled_ids[1..];
2122 is_enabled = false;
2123 }
2124 (bracket, is_enabled)
2125 })
2126 }
2127
2128 pub fn should_autoclose_before(&self, c: char) -> bool {
2129 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
2130 }
2131
2132 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
2133 let config = &self.language.config;
2134 let opt_in_servers = &config.scope_opt_in_language_servers;
2135 if opt_in_servers.contains(name) {
2136 if let Some(over) = self.config_override() {
2137 over.opt_into_language_servers.contains(name)
2138 } else {
2139 false
2140 }
2141 } else {
2142 true
2143 }
2144 }
2145
2146 pub fn override_name(&self) -> Option<&str> {
2147 let id = self.override_id?;
2148 let grammar = self.language.grammar.as_ref()?;
2149 let override_config = grammar.override_config.as_ref()?;
2150 override_config.values.get(&id).map(|e| e.name.as_str())
2151 }
2152
2153 fn config_override(&self) -> Option<&LanguageConfigOverride> {
2154 let id = self.override_id?;
2155 let grammar = self.language.grammar.as_ref()?;
2156 let override_config = grammar.override_config.as_ref()?;
2157 override_config.values.get(&id).map(|e| &e.value)
2158 }
2159}
2160
2161impl Hash for Language {
2162 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2163 self.id.hash(state)
2164 }
2165}
2166
2167impl PartialEq for Language {
2168 fn eq(&self, other: &Self) -> bool {
2169 self.id.eq(&other.id)
2170 }
2171}
2172
2173impl Eq for Language {}
2174
2175impl Debug for Language {
2176 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2177 f.debug_struct("Language")
2178 .field("name", &self.config.name)
2179 .finish()
2180 }
2181}
2182
2183impl Grammar {
2184 pub fn id(&self) -> GrammarId {
2185 self.id
2186 }
2187
2188 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
2189 with_parser(|parser| {
2190 parser
2191 .set_language(&self.ts_language)
2192 .expect("incompatible grammar");
2193 let mut chunks = text.chunks_in_range(0..text.len());
2194 parser
2195 .parse_with_options(
2196 &mut move |offset, _| {
2197 chunks.seek(offset);
2198 chunks.next().unwrap_or("").as_bytes()
2199 },
2200 old_tree.as_ref(),
2201 None,
2202 )
2203 .unwrap()
2204 })
2205 }
2206
2207 pub fn highlight_map(&self) -> HighlightMap {
2208 self.highlight_map.lock().clone()
2209 }
2210
2211 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
2212 let capture_id = self
2213 .highlights_config
2214 .as_ref()?
2215 .query
2216 .capture_index_for_name(name)?;
2217 Some(self.highlight_map.lock().get(capture_id))
2218 }
2219
2220 pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2221 self.debug_variables_config.as_ref()
2222 }
2223
2224 pub fn imports_config(&self) -> Option<&ImportsConfig> {
2225 self.imports_config.as_ref()
2226 }
2227}
2228
2229impl CodeLabelBuilder {
2230 pub fn respan_filter_range(&mut self, filter_text: Option<&str>) {
2231 self.filter_range = filter_text
2232 .and_then(|filter| self.text.find(filter).map(|ix| ix..ix + filter.len()))
2233 .unwrap_or(0..self.text.len());
2234 }
2235
2236 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2237 let start_ix = self.text.len();
2238 self.text.push_str(text);
2239 if let Some(highlight) = highlight {
2240 let end_ix = self.text.len();
2241 self.runs.push((start_ix..end_ix, highlight));
2242 }
2243 }
2244
2245 pub fn build(mut self) -> CodeLabel {
2246 if self.filter_range.end == 0 {
2247 self.respan_filter_range(None);
2248 }
2249 CodeLabel {
2250 text: self.text,
2251 runs: self.runs,
2252 filter_range: self.filter_range,
2253 }
2254 }
2255}
2256
2257impl CodeLabel {
2258 pub fn fallback_for_completion(
2259 item: &lsp::CompletionItem,
2260 language: Option<&Language>,
2261 ) -> Self {
2262 let highlight_id = item.kind.and_then(|kind| {
2263 let grammar = language?.grammar()?;
2264 use lsp::CompletionItemKind as Kind;
2265 match kind {
2266 Kind::CLASS => grammar.highlight_id_for_name("type"),
2267 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2268 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2269 Kind::ENUM => grammar
2270 .highlight_id_for_name("enum")
2271 .or_else(|| grammar.highlight_id_for_name("type")),
2272 Kind::ENUM_MEMBER => grammar
2273 .highlight_id_for_name("variant")
2274 .or_else(|| grammar.highlight_id_for_name("property")),
2275 Kind::FIELD => grammar.highlight_id_for_name("property"),
2276 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2277 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2278 Kind::METHOD => grammar
2279 .highlight_id_for_name("function.method")
2280 .or_else(|| grammar.highlight_id_for_name("function")),
2281 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2282 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2283 Kind::STRUCT => grammar.highlight_id_for_name("type"),
2284 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2285 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2286 _ => None,
2287 }
2288 });
2289
2290 let label = &item.label;
2291 let label_length = label.len();
2292 let runs = highlight_id
2293 .map(|highlight_id| vec![(0..label_length, highlight_id)])
2294 .unwrap_or_default();
2295 let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2296 format!("{label} {detail}")
2297 } else if let Some(description) = item
2298 .label_details
2299 .as_ref()
2300 .and_then(|label_details| label_details.description.as_deref())
2301 .filter(|description| description != label)
2302 {
2303 format!("{label} {description}")
2304 } else {
2305 label.clone()
2306 };
2307 let filter_range = item
2308 .filter_text
2309 .as_deref()
2310 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2311 .unwrap_or(0..label_length);
2312 Self {
2313 text,
2314 runs,
2315 filter_range,
2316 }
2317 }
2318
2319 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2320 Self::filtered(text.clone(), text.len(), filter_text, Vec::new())
2321 }
2322
2323 pub fn filtered(
2324 text: String,
2325 label_len: usize,
2326 filter_text: Option<&str>,
2327 runs: Vec<(Range<usize>, HighlightId)>,
2328 ) -> Self {
2329 assert!(label_len <= text.len());
2330 let filter_range = filter_text
2331 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2332 .unwrap_or(0..label_len);
2333 Self::new(text, filter_range, runs)
2334 }
2335
2336 pub fn new(
2337 text: String,
2338 filter_range: Range<usize>,
2339 runs: Vec<(Range<usize>, HighlightId)>,
2340 ) -> Self {
2341 assert!(
2342 text.get(filter_range.clone()).is_some(),
2343 "invalid filter range"
2344 );
2345 runs.iter().for_each(|(range, _)| {
2346 assert!(text.get(range.clone()).is_some(), "invalid run range");
2347 });
2348 Self {
2349 runs,
2350 filter_range,
2351 text,
2352 }
2353 }
2354
2355 pub fn text(&self) -> &str {
2356 self.text.as_str()
2357 }
2358
2359 pub fn filter_text(&self) -> &str {
2360 &self.text[self.filter_range.clone()]
2361 }
2362}
2363
2364impl From<String> for CodeLabel {
2365 fn from(value: String) -> Self {
2366 Self::plain(value, None)
2367 }
2368}
2369
2370impl From<&str> for CodeLabel {
2371 fn from(value: &str) -> Self {
2372 Self::plain(value.to_string(), None)
2373 }
2374}
2375
2376impl Ord for LanguageMatcher {
2377 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2378 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2379 self.first_line_pattern
2380 .as_ref()
2381 .map(Regex::as_str)
2382 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2383 })
2384 }
2385}
2386
2387impl PartialOrd for LanguageMatcher {
2388 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2389 Some(self.cmp(other))
2390 }
2391}
2392
2393impl Eq for LanguageMatcher {}
2394
2395impl PartialEq for LanguageMatcher {
2396 fn eq(&self, other: &Self) -> bool {
2397 self.path_suffixes == other.path_suffixes
2398 && self.first_line_pattern.as_ref().map(Regex::as_str)
2399 == other.first_line_pattern.as_ref().map(Regex::as_str)
2400 }
2401}
2402
2403#[cfg(any(test, feature = "test-support"))]
2404impl Default for FakeLspAdapter {
2405 fn default() -> Self {
2406 Self {
2407 name: "the-fake-language-server",
2408 capabilities: lsp::LanguageServer::full_capabilities(),
2409 initializer: None,
2410 disk_based_diagnostics_progress_token: None,
2411 initialization_options: None,
2412 disk_based_diagnostics_sources: Vec::new(),
2413 prettier_plugins: Vec::new(),
2414 language_server_binary: LanguageServerBinary {
2415 path: "/the/fake/lsp/path".into(),
2416 arguments: vec![],
2417 env: Default::default(),
2418 },
2419 label_for_completion: None,
2420 }
2421 }
2422}
2423
2424#[cfg(any(test, feature = "test-support"))]
2425impl LspInstaller for FakeLspAdapter {
2426 type BinaryVersion = ();
2427
2428 async fn fetch_latest_server_version(
2429 &self,
2430 _: &dyn LspAdapterDelegate,
2431 _: bool,
2432 _: &mut AsyncApp,
2433 ) -> Result<Self::BinaryVersion> {
2434 unreachable!()
2435 }
2436
2437 async fn check_if_user_installed(
2438 &self,
2439 _: &dyn LspAdapterDelegate,
2440 _: Option<Toolchain>,
2441 _: &AsyncApp,
2442 ) -> Option<LanguageServerBinary> {
2443 Some(self.language_server_binary.clone())
2444 }
2445
2446 async fn fetch_server_binary(
2447 &self,
2448 _: (),
2449 _: PathBuf,
2450 _: &dyn LspAdapterDelegate,
2451 ) -> Result<LanguageServerBinary> {
2452 unreachable!();
2453 }
2454
2455 async fn cached_server_binary(
2456 &self,
2457 _: PathBuf,
2458 _: &dyn LspAdapterDelegate,
2459 ) -> Option<LanguageServerBinary> {
2460 unreachable!();
2461 }
2462}
2463
2464#[cfg(any(test, feature = "test-support"))]
2465#[async_trait(?Send)]
2466impl LspAdapter for FakeLspAdapter {
2467 fn name(&self) -> LanguageServerName {
2468 LanguageServerName(self.name.into())
2469 }
2470
2471 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2472 self.disk_based_diagnostics_sources.clone()
2473 }
2474
2475 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2476 self.disk_based_diagnostics_progress_token.clone()
2477 }
2478
2479 async fn initialization_options(
2480 self: Arc<Self>,
2481 _: &Arc<dyn LspAdapterDelegate>,
2482 ) -> Result<Option<Value>> {
2483 Ok(self.initialization_options.clone())
2484 }
2485
2486 async fn label_for_completion(
2487 &self,
2488 item: &lsp::CompletionItem,
2489 language: &Arc<Language>,
2490 ) -> Option<CodeLabel> {
2491 let label_for_completion = self.label_for_completion.as_ref()?;
2492 label_for_completion(item, language)
2493 }
2494
2495 fn is_extension(&self) -> bool {
2496 false
2497 }
2498}
2499
2500enum Capture<'a> {
2501 Required(&'static str, &'a mut u32),
2502 Optional(&'static str, &'a mut Option<u32>),
2503}
2504
2505fn populate_capture_indices(
2506 query: &Query,
2507 language_name: &LanguageName,
2508 query_type: &str,
2509 expected_prefixes: &[&str],
2510 captures: &mut [Capture<'_>],
2511) -> bool {
2512 let mut found_required_indices = Vec::new();
2513 'outer: for (ix, name) in query.capture_names().iter().enumerate() {
2514 for (required_ix, capture) in captures.iter_mut().enumerate() {
2515 match capture {
2516 Capture::Required(capture_name, index) if capture_name == name => {
2517 **index = ix as u32;
2518 found_required_indices.push(required_ix);
2519 continue 'outer;
2520 }
2521 Capture::Optional(capture_name, index) if capture_name == name => {
2522 **index = Some(ix as u32);
2523 continue 'outer;
2524 }
2525 _ => {}
2526 }
2527 }
2528 if !name.starts_with("_")
2529 && !expected_prefixes
2530 .iter()
2531 .any(|&prefix| name.starts_with(prefix))
2532 {
2533 log::warn!(
2534 "unrecognized capture name '{}' in {} {} TreeSitter query \
2535 (suppress this warning by prefixing with '_')",
2536 name,
2537 language_name,
2538 query_type
2539 );
2540 }
2541 }
2542 let mut missing_required_captures = Vec::new();
2543 for (capture_ix, capture) in captures.iter().enumerate() {
2544 if let Capture::Required(capture_name, _) = capture
2545 && !found_required_indices.contains(&capture_ix)
2546 {
2547 missing_required_captures.push(*capture_name);
2548 }
2549 }
2550 let success = missing_required_captures.is_empty();
2551 if !success {
2552 log::error!(
2553 "missing required capture(s) in {} {} TreeSitter query: {}",
2554 language_name,
2555 query_type,
2556 missing_required_captures.join(", ")
2557 );
2558 }
2559 success
2560}
2561
2562pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2563 lsp::Position::new(point.row, point.column)
2564}
2565
2566pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2567 Unclipped(PointUtf16::new(point.line, point.character))
2568}
2569
2570pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2571 anyhow::ensure!(
2572 range.start <= range.end,
2573 "Inverted range provided to an LSP request: {:?}-{:?}",
2574 range.start,
2575 range.end
2576 );
2577 Ok(lsp::Range {
2578 start: point_to_lsp(range.start),
2579 end: point_to_lsp(range.end),
2580 })
2581}
2582
2583pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2584 let mut start = point_from_lsp(range.start);
2585 let mut end = point_from_lsp(range.end);
2586 if start > end {
2587 // We debug instead of warn so that this is not logged by default unless explicitly requested.
2588 // Using warn would write to the log file, and since we receive an enormous amount of
2589 // range_from_lsp calls (especially during completions), that can hang the main thread.
2590 //
2591 // See issue #36223.
2592 zlog::debug!("range_from_lsp called with inverted range {start:?}-{end:?}");
2593 mem::swap(&mut start, &mut end);
2594 }
2595 start..end
2596}
2597
2598#[doc(hidden)]
2599#[cfg(any(test, feature = "test-support"))]
2600pub fn rust_lang() -> Arc<Language> {
2601 use std::borrow::Cow;
2602
2603 let language = Language::new(
2604 LanguageConfig {
2605 name: "Rust".into(),
2606 matcher: LanguageMatcher {
2607 path_suffixes: vec!["rs".to_string()],
2608 ..Default::default()
2609 },
2610 line_comments: vec!["// ".into(), "/// ".into(), "//! ".into()],
2611 ..Default::default()
2612 },
2613 Some(tree_sitter_rust::LANGUAGE.into()),
2614 )
2615 .with_queries(LanguageQueries {
2616 outline: Some(Cow::from(include_str!(
2617 "../../languages/src/rust/outline.scm"
2618 ))),
2619 indents: Some(Cow::from(
2620 r#"
2621[
2622 ((where_clause) _ @end)
2623 (field_expression)
2624 (call_expression)
2625 (assignment_expression)
2626 (let_declaration)
2627 (let_chain)
2628 (await_expression)
2629] @indent
2630
2631(_ "[" "]" @end) @indent
2632(_ "<" ">" @end) @indent
2633(_ "{" "}" @end) @indent
2634(_ "(" ")" @end) @indent"#,
2635 )),
2636 brackets: Some(Cow::from(
2637 r#"
2638("(" @open ")" @close)
2639("[" @open "]" @close)
2640("{" @open "}" @close)
2641("<" @open ">" @close)
2642("\"" @open "\"" @close)
2643(closure_parameters "|" @open "|" @close)"#,
2644 )),
2645 text_objects: Some(Cow::from(
2646 r#"
2647(function_item
2648 body: (_
2649 "{"
2650 (_)* @function.inside
2651 "}" )) @function.around
2652 "#,
2653 )),
2654 ..LanguageQueries::default()
2655 })
2656 .expect("Could not parse queries");
2657 Arc::new(language)
2658}
2659
2660#[cfg(test)]
2661mod tests {
2662 use super::*;
2663 use gpui::TestAppContext;
2664 use pretty_assertions::assert_matches;
2665
2666 #[gpui::test(iterations = 10)]
2667 async fn test_language_loading(cx: &mut TestAppContext) {
2668 let languages = LanguageRegistry::test(cx.executor());
2669 let languages = Arc::new(languages);
2670 languages.register_native_grammars([
2671 ("json", tree_sitter_json::LANGUAGE),
2672 ("rust", tree_sitter_rust::LANGUAGE),
2673 ]);
2674 languages.register_test_language(LanguageConfig {
2675 name: "JSON".into(),
2676 grammar: Some("json".into()),
2677 matcher: LanguageMatcher {
2678 path_suffixes: vec!["json".into()],
2679 ..Default::default()
2680 },
2681 ..Default::default()
2682 });
2683 languages.register_test_language(LanguageConfig {
2684 name: "Rust".into(),
2685 grammar: Some("rust".into()),
2686 matcher: LanguageMatcher {
2687 path_suffixes: vec!["rs".into()],
2688 ..Default::default()
2689 },
2690 ..Default::default()
2691 });
2692 assert_eq!(
2693 languages.language_names(),
2694 &[
2695 LanguageName::new("JSON"),
2696 LanguageName::new("Plain Text"),
2697 LanguageName::new("Rust"),
2698 ]
2699 );
2700
2701 let rust1 = languages.language_for_name("Rust");
2702 let rust2 = languages.language_for_name("Rust");
2703
2704 // Ensure language is still listed even if it's being loaded.
2705 assert_eq!(
2706 languages.language_names(),
2707 &[
2708 LanguageName::new("JSON"),
2709 LanguageName::new("Plain Text"),
2710 LanguageName::new("Rust"),
2711 ]
2712 );
2713
2714 let (rust1, rust2) = futures::join!(rust1, rust2);
2715 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2716
2717 // Ensure language is still listed even after loading it.
2718 assert_eq!(
2719 languages.language_names(),
2720 &[
2721 LanguageName::new("JSON"),
2722 LanguageName::new("Plain Text"),
2723 LanguageName::new("Rust"),
2724 ]
2725 );
2726
2727 // Loading an unknown language returns an error.
2728 assert!(languages.language_for_name("Unknown").await.is_err());
2729 }
2730
2731 #[gpui::test]
2732 async fn test_completion_label_omits_duplicate_data() {
2733 let regular_completion_item_1 = lsp::CompletionItem {
2734 label: "regular1".to_string(),
2735 detail: Some("detail1".to_string()),
2736 label_details: Some(lsp::CompletionItemLabelDetails {
2737 detail: None,
2738 description: Some("description 1".to_string()),
2739 }),
2740 ..lsp::CompletionItem::default()
2741 };
2742
2743 let regular_completion_item_2 = lsp::CompletionItem {
2744 label: "regular2".to_string(),
2745 label_details: Some(lsp::CompletionItemLabelDetails {
2746 detail: None,
2747 description: Some("description 2".to_string()),
2748 }),
2749 ..lsp::CompletionItem::default()
2750 };
2751
2752 let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2753 detail: Some(regular_completion_item_1.label.clone()),
2754 ..regular_completion_item_1.clone()
2755 };
2756
2757 let completion_item_with_duplicate_detail = lsp::CompletionItem {
2758 detail: Some(regular_completion_item_1.label.clone()),
2759 label_details: None,
2760 ..regular_completion_item_1.clone()
2761 };
2762
2763 let completion_item_with_duplicate_description = lsp::CompletionItem {
2764 label_details: Some(lsp::CompletionItemLabelDetails {
2765 detail: None,
2766 description: Some(regular_completion_item_2.label.clone()),
2767 }),
2768 ..regular_completion_item_2.clone()
2769 };
2770
2771 assert_eq!(
2772 CodeLabel::fallback_for_completion(®ular_completion_item_1, None).text,
2773 format!(
2774 "{} {}",
2775 regular_completion_item_1.label,
2776 regular_completion_item_1.detail.unwrap()
2777 ),
2778 "LSP completion items with both detail and label_details.description should prefer detail"
2779 );
2780 assert_eq!(
2781 CodeLabel::fallback_for_completion(®ular_completion_item_2, None).text,
2782 format!(
2783 "{} {}",
2784 regular_completion_item_2.label,
2785 regular_completion_item_2
2786 .label_details
2787 .as_ref()
2788 .unwrap()
2789 .description
2790 .as_ref()
2791 .unwrap()
2792 ),
2793 "LSP completion items without detail but with label_details.description should use that"
2794 );
2795 assert_eq!(
2796 CodeLabel::fallback_for_completion(
2797 &completion_item_with_duplicate_detail_and_proper_description,
2798 None
2799 )
2800 .text,
2801 format!(
2802 "{} {}",
2803 regular_completion_item_1.label,
2804 regular_completion_item_1
2805 .label_details
2806 .as_ref()
2807 .unwrap()
2808 .description
2809 .as_ref()
2810 .unwrap()
2811 ),
2812 "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2813 );
2814 assert_eq!(
2815 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2816 regular_completion_item_1.label,
2817 "LSP completion items with duplicate label and detail, should omit the detail"
2818 );
2819 assert_eq!(
2820 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2821 .text,
2822 regular_completion_item_2.label,
2823 "LSP completion items with duplicate label and detail, should omit the detail"
2824 );
2825 }
2826
2827 #[test]
2828 fn test_deserializing_comments_backwards_compat() {
2829 // current version of `block_comment` and `documentation_comment` work
2830 {
2831 let config: LanguageConfig = ::toml::from_str(
2832 r#"
2833 name = "Foo"
2834 block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
2835 documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
2836 "#,
2837 )
2838 .unwrap();
2839 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2840 assert_matches!(
2841 config.documentation_comment,
2842 Some(BlockCommentConfig { .. })
2843 );
2844
2845 let block_config = config.block_comment.unwrap();
2846 assert_eq!(block_config.start.as_ref(), "a");
2847 assert_eq!(block_config.end.as_ref(), "b");
2848 assert_eq!(block_config.prefix.as_ref(), "c");
2849 assert_eq!(block_config.tab_size, 1);
2850
2851 let doc_config = config.documentation_comment.unwrap();
2852 assert_eq!(doc_config.start.as_ref(), "d");
2853 assert_eq!(doc_config.end.as_ref(), "e");
2854 assert_eq!(doc_config.prefix.as_ref(), "f");
2855 assert_eq!(doc_config.tab_size, 2);
2856 }
2857
2858 // former `documentation` setting is read into `documentation_comment`
2859 {
2860 let config: LanguageConfig = ::toml::from_str(
2861 r#"
2862 name = "Foo"
2863 documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
2864 "#,
2865 )
2866 .unwrap();
2867 assert_matches!(
2868 config.documentation_comment,
2869 Some(BlockCommentConfig { .. })
2870 );
2871
2872 let config = config.documentation_comment.unwrap();
2873 assert_eq!(config.start.as_ref(), "a");
2874 assert_eq!(config.end.as_ref(), "b");
2875 assert_eq!(config.prefix.as_ref(), "c");
2876 assert_eq!(config.tab_size, 1);
2877 }
2878
2879 // old block_comment format is read into BlockCommentConfig
2880 {
2881 let config: LanguageConfig = ::toml::from_str(
2882 r#"
2883 name = "Foo"
2884 block_comment = ["a", "b"]
2885 "#,
2886 )
2887 .unwrap();
2888 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2889
2890 let config = config.block_comment.unwrap();
2891 assert_eq!(config.start.as_ref(), "a");
2892 assert_eq!(config.end.as_ref(), "b");
2893 assert_eq!(config.prefix.as_ref(), "");
2894 assert_eq!(config.tab_size, 0);
2895 }
2896 }
2897}