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