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