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