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