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