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