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