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