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 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::{AtomicU64, 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::serde::default_true;
74
75pub use buffer::Operation;
76pub use buffer::*;
77pub use diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
78pub use language_registry::{
79 AvailableLanguage, BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry,
80 QUERY_FILENAME_PREFIXES,
81};
82pub use lsp::{LanguageServerId, LanguageServerName};
83pub use outline::*;
84pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer, ToTreeSitterPoint, TreeSitterOptions};
85pub use text::{AnchorRangeExt, LineEnding};
86pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
87
88/// Initializes the `language` crate.
89///
90/// This should be called before making use of items from the create.
91pub fn init(cx: &mut App) {
92 language_settings::init(cx);
93}
94
95static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
96static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
97
98pub fn with_parser<F, R>(func: F) -> R
99where
100 F: FnOnce(&mut Parser) -> R,
101{
102 let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
103 let mut parser = Parser::new();
104 parser
105 .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
106 .unwrap();
107 parser
108 });
109 parser.set_included_ranges(&[]).unwrap();
110 let result = func(&mut parser);
111 PARSERS.lock().push(parser);
112 result
113}
114
115pub fn with_query_cursor<F, R>(func: F) -> R
116where
117 F: FnOnce(&mut QueryCursor) -> R,
118{
119 let mut cursor = QueryCursorHandle::new();
120 func(cursor.deref_mut())
121}
122
123static NEXT_LANGUAGE_ID: AtomicUsize = AtomicUsize::new(0);
124static NEXT_GRAMMAR_ID: AtomicUsize = AtomicUsize::new(0);
125static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
126 wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
127});
128
129/// A shared grammar for plain text, exposed for reuse by downstream crates.
130pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
131 Arc::new(Language::new(
132 LanguageConfig {
133 name: "Plain Text".into(),
134 soft_wrap: Some(SoftWrap::EditorWidth),
135 matcher: LanguageMatcher {
136 path_suffixes: vec!["txt".to_owned()],
137 first_line_pattern: None,
138 },
139 ..Default::default()
140 },
141 None,
142 ))
143});
144
145/// Types that represent a position in a buffer, and can be converted into
146/// an LSP position, to send to a language server.
147pub trait ToLspPosition {
148 /// Converts the value into an LSP position.
149 fn to_lsp_position(self) -> lsp::Position;
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Hash)]
153pub struct Location {
154 pub buffer: Entity<Buffer>,
155 pub range: Range<Anchor>,
156}
157
158type ServerBinaryCache = futures::lock::Mutex<Option<(bool, LanguageServerBinary)>>;
159
160/// Represents a Language Server, with certain cached sync properties.
161/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
162/// once at startup, and caches the results.
163pub struct CachedLspAdapter {
164 pub name: LanguageServerName,
165 pub disk_based_diagnostic_sources: Vec<String>,
166 pub disk_based_diagnostics_progress_token: Option<String>,
167 language_ids: HashMap<LanguageName, String>,
168 pub adapter: Arc<dyn LspAdapter>,
169 pub reinstall_attempt_count: AtomicU64,
170 cached_binary: ServerBinaryCache,
171}
172
173impl Debug for CachedLspAdapter {
174 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175 f.debug_struct("CachedLspAdapter")
176 .field("name", &self.name)
177 .field(
178 "disk_based_diagnostic_sources",
179 &self.disk_based_diagnostic_sources,
180 )
181 .field(
182 "disk_based_diagnostics_progress_token",
183 &self.disk_based_diagnostics_progress_token,
184 )
185 .field("language_ids", &self.language_ids)
186 .field("reinstall_attempt_count", &self.reinstall_attempt_count)
187 .finish_non_exhaustive()
188 }
189}
190
191impl CachedLspAdapter {
192 pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
193 let name = adapter.name();
194 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
195 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
196 let language_ids = adapter.language_ids();
197
198 Arc::new(CachedLspAdapter {
199 name,
200 disk_based_diagnostic_sources,
201 disk_based_diagnostics_progress_token,
202 language_ids,
203 adapter,
204 cached_binary: Default::default(),
205 reinstall_attempt_count: AtomicU64::new(0),
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: PathBuf) -> 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 preferred debuggers for this language.
785 #[serde(default)]
786 pub debuggers: IndexSet<SharedString>,
787}
788
789#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
790pub struct DecreaseIndentConfig {
791 #[serde(default, deserialize_with = "deserialize_regex")]
792 #[schemars(schema_with = "regex_json_schema")]
793 pub pattern: Option<Regex>,
794 #[serde(default)]
795 pub valid_after: Vec<String>,
796}
797
798#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
799pub struct LanguageMatcher {
800 /// 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`.
801 #[serde(default)]
802 pub path_suffixes: Vec<String>,
803 /// A regex pattern that determines whether the language should be assigned to a file or not.
804 #[serde(
805 default,
806 serialize_with = "serialize_regex",
807 deserialize_with = "deserialize_regex"
808 )]
809 #[schemars(schema_with = "regex_json_schema")]
810 pub first_line_pattern: Option<Regex>,
811}
812
813/// The configuration for JSX tag auto-closing.
814#[derive(Clone, Deserialize, JsonSchema)]
815pub struct JsxTagAutoCloseConfig {
816 /// The name of the node for a opening tag
817 pub open_tag_node_name: String,
818 /// The name of the node for an closing tag
819 pub close_tag_node_name: String,
820 /// The name of the node for a complete element with children for open and close tags
821 pub jsx_element_node_name: String,
822 /// The name of the node found within both opening and closing
823 /// tags that describes the tag name
824 pub tag_name_node_name: String,
825 /// Alternate Node names for tag names.
826 /// Specifically needed as TSX represents the name in `<Foo.Bar>`
827 /// as `member_expression` rather than `identifier` as usual
828 #[serde(default)]
829 pub tag_name_node_name_alternates: Vec<String>,
830 /// Some grammars are smart enough to detect a closing tag
831 /// that is not valid i.e. doesn't match it's corresponding
832 /// opening tag or does not have a corresponding opening tag
833 /// This should be set to the name of the node for invalid
834 /// closing tags if the grammar contains such a node, otherwise
835 /// detecting already closed tags will not work properly
836 #[serde(default)]
837 pub erroneous_close_tag_node_name: Option<String>,
838 /// See above for erroneous_close_tag_node_name for details
839 /// This should be set if the node used for the tag name
840 /// within erroneous closing tags is different from the
841 /// normal tag name node name
842 #[serde(default)]
843 pub erroneous_close_tag_name_node_name: Option<String>,
844}
845
846/// The configuration for block comments for this language.
847#[derive(Clone, Debug, JsonSchema, PartialEq)]
848pub struct BlockCommentConfig {
849 /// A start tag of block comment.
850 pub start: Arc<str>,
851 /// A end tag of block comment.
852 pub end: Arc<str>,
853 /// A character to add as a prefix when a new line is added to a block comment.
854 pub prefix: Arc<str>,
855 /// A indent to add for prefix and end line upon new line.
856 pub tab_size: u32,
857}
858
859impl<'de> Deserialize<'de> for BlockCommentConfig {
860 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
861 where
862 D: Deserializer<'de>,
863 {
864 #[derive(Deserialize)]
865 #[serde(untagged)]
866 enum BlockCommentConfigHelper {
867 New {
868 start: Arc<str>,
869 end: Arc<str>,
870 prefix: Arc<str>,
871 tab_size: u32,
872 },
873 Old([Arc<str>; 2]),
874 }
875
876 match BlockCommentConfigHelper::deserialize(deserializer)? {
877 BlockCommentConfigHelper::New {
878 start,
879 end,
880 prefix,
881 tab_size,
882 } => Ok(BlockCommentConfig {
883 start,
884 end,
885 prefix,
886 tab_size,
887 }),
888 BlockCommentConfigHelper::Old([start, end]) => Ok(BlockCommentConfig {
889 start,
890 end,
891 prefix: "".into(),
892 tab_size: 0,
893 }),
894 }
895 }
896}
897
898/// Represents a language for the given range. Some languages (e.g. HTML)
899/// interleave several languages together, thus a single buffer might actually contain
900/// several nested scopes.
901#[derive(Clone, Debug)]
902pub struct LanguageScope {
903 language: Arc<Language>,
904 override_id: Option<u32>,
905}
906
907#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
908pub struct LanguageConfigOverride {
909 #[serde(default)]
910 pub line_comments: Override<Vec<Arc<str>>>,
911 #[serde(default)]
912 pub block_comment: Override<BlockCommentConfig>,
913 #[serde(skip)]
914 pub disabled_bracket_ixs: Vec<u16>,
915 #[serde(default)]
916 pub word_characters: Override<HashSet<char>>,
917 #[serde(default)]
918 pub completion_query_characters: Override<HashSet<char>>,
919 #[serde(default)]
920 pub opt_into_language_servers: Vec<LanguageServerName>,
921 #[serde(default)]
922 pub prefer_label_for_snippet: Option<bool>,
923}
924
925#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
926#[serde(untagged)]
927pub enum Override<T> {
928 Remove { remove: bool },
929 Set(T),
930}
931
932impl<T> Default for Override<T> {
933 fn default() -> Self {
934 Override::Remove { remove: false }
935 }
936}
937
938impl<T> Override<T> {
939 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
940 match this {
941 Some(Self::Set(value)) => Some(value),
942 Some(Self::Remove { remove: true }) => None,
943 Some(Self::Remove { remove: false }) | None => original,
944 }
945 }
946}
947
948impl Default for LanguageConfig {
949 fn default() -> Self {
950 Self {
951 name: LanguageName::new(""),
952 code_fence_block_name: None,
953 grammar: None,
954 matcher: LanguageMatcher::default(),
955 brackets: Default::default(),
956 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
957 auto_indent_on_paste: None,
958 increase_indent_pattern: Default::default(),
959 decrease_indent_pattern: Default::default(),
960 decrease_indent_patterns: Default::default(),
961 autoclose_before: Default::default(),
962 line_comments: Default::default(),
963 block_comment: Default::default(),
964 documentation_comment: Default::default(),
965 rewrap_prefixes: Default::default(),
966 scope_opt_in_language_servers: Default::default(),
967 overrides: Default::default(),
968 word_characters: Default::default(),
969 collapsed_placeholder: Default::default(),
970 hard_tabs: None,
971 tab_size: None,
972 soft_wrap: None,
973 wrap_characters: None,
974 prettier_parser_name: None,
975 hidden: false,
976 jsx_tag_auto_close: None,
977 completion_query_characters: Default::default(),
978 debuggers: Default::default(),
979 }
980 }
981}
982
983#[derive(Clone, Debug, Deserialize, JsonSchema)]
984pub struct WrapCharactersConfig {
985 /// Opening token split into a prefix and suffix. The first caret goes
986 /// after the prefix (i.e., between prefix and suffix).
987 pub start_prefix: String,
988 pub start_suffix: String,
989 /// Closing token split into a prefix and suffix. The second caret goes
990 /// after the prefix (i.e., between prefix and suffix).
991 pub end_prefix: String,
992 pub end_suffix: String,
993}
994
995fn auto_indent_using_last_non_empty_line_default() -> bool {
996 true
997}
998
999fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
1000 let source = Option::<String>::deserialize(d)?;
1001 if let Some(source) = source {
1002 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
1003 } else {
1004 Ok(None)
1005 }
1006}
1007
1008fn regex_json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
1009 json_schema!({
1010 "type": "string"
1011 })
1012}
1013
1014fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
1015where
1016 S: Serializer,
1017{
1018 match regex {
1019 Some(regex) => serializer.serialize_str(regex.as_str()),
1020 None => serializer.serialize_none(),
1021 }
1022}
1023
1024fn deserialize_regex_vec<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<Regex>, D::Error> {
1025 let sources = Vec::<String>::deserialize(d)?;
1026 sources
1027 .into_iter()
1028 .map(|source| regex::Regex::new(&source))
1029 .collect::<Result<_, _>>()
1030 .map_err(de::Error::custom)
1031}
1032
1033fn regex_vec_json_schema(_: &mut SchemaGenerator) -> schemars::Schema {
1034 json_schema!({
1035 "type": "array",
1036 "items": { "type": "string" }
1037 })
1038}
1039
1040#[doc(hidden)]
1041#[cfg(any(test, feature = "test-support"))]
1042pub struct FakeLspAdapter {
1043 pub name: &'static str,
1044 pub initialization_options: Option<Value>,
1045 pub prettier_plugins: Vec<&'static str>,
1046 pub disk_based_diagnostics_progress_token: Option<String>,
1047 pub disk_based_diagnostics_sources: Vec<String>,
1048 pub language_server_binary: LanguageServerBinary,
1049
1050 pub capabilities: lsp::ServerCapabilities,
1051 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
1052 pub label_for_completion: Option<
1053 Box<
1054 dyn 'static
1055 + Send
1056 + Sync
1057 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
1058 >,
1059 >,
1060}
1061
1062/// Configuration of handling bracket pairs for a given language.
1063///
1064/// This struct includes settings for defining which pairs of characters are considered brackets and
1065/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
1066#[derive(Clone, Debug, Default, JsonSchema)]
1067#[schemars(with = "Vec::<BracketPairContent>")]
1068pub struct BracketPairConfig {
1069 /// A list of character pairs that should be treated as brackets in the context of a given language.
1070 pub pairs: Vec<BracketPair>,
1071 /// A list of tree-sitter scopes for which a given bracket should not be active.
1072 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
1073 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
1074}
1075
1076impl BracketPairConfig {
1077 pub fn is_closing_brace(&self, c: char) -> bool {
1078 self.pairs.iter().any(|pair| pair.end.starts_with(c))
1079 }
1080}
1081
1082#[derive(Deserialize, JsonSchema)]
1083pub struct BracketPairContent {
1084 #[serde(flatten)]
1085 pub bracket_pair: BracketPair,
1086 #[serde(default)]
1087 pub not_in: Vec<String>,
1088}
1089
1090impl<'de> Deserialize<'de> for BracketPairConfig {
1091 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1092 where
1093 D: Deserializer<'de>,
1094 {
1095 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1096 let (brackets, disabled_scopes_by_bracket_ix) = result
1097 .into_iter()
1098 .map(|entry| (entry.bracket_pair, entry.not_in))
1099 .unzip();
1100
1101 Ok(BracketPairConfig {
1102 pairs: brackets,
1103 disabled_scopes_by_bracket_ix,
1104 })
1105 }
1106}
1107
1108/// Describes a single bracket pair and how an editor should react to e.g. inserting
1109/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1110#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1111pub struct BracketPair {
1112 /// Starting substring for a bracket.
1113 pub start: String,
1114 /// Ending substring for a bracket.
1115 pub end: String,
1116 /// True if `end` should be automatically inserted right after `start` characters.
1117 pub close: bool,
1118 /// True if selected text should be surrounded by `start` and `end` characters.
1119 #[serde(default = "default_true")]
1120 pub surround: bool,
1121 /// True if an extra newline should be inserted while the cursor is in the middle
1122 /// of that bracket pair.
1123 pub newline: bool,
1124}
1125
1126#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1127pub struct LanguageId(usize);
1128
1129impl LanguageId {
1130 pub(crate) fn new() -> Self {
1131 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1132 }
1133}
1134
1135pub struct Language {
1136 pub(crate) id: LanguageId,
1137 pub(crate) config: LanguageConfig,
1138 pub(crate) grammar: Option<Arc<Grammar>>,
1139 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1140 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1141 pub(crate) manifest_name: Option<ManifestName>,
1142}
1143
1144#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1145pub struct GrammarId(pub usize);
1146
1147impl GrammarId {
1148 pub(crate) fn new() -> Self {
1149 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1150 }
1151}
1152
1153pub struct Grammar {
1154 id: GrammarId,
1155 pub ts_language: tree_sitter::Language,
1156 pub(crate) error_query: Option<Query>,
1157 pub(crate) highlights_query: Option<Query>,
1158 pub(crate) brackets_config: Option<BracketsConfig>,
1159 pub(crate) redactions_config: Option<RedactionConfig>,
1160 pub(crate) runnable_config: Option<RunnableConfig>,
1161 pub(crate) indents_config: Option<IndentConfig>,
1162 pub outline_config: Option<OutlineConfig>,
1163 pub text_object_config: Option<TextObjectConfig>,
1164 pub embedding_config: Option<EmbeddingConfig>,
1165 pub(crate) injection_config: Option<InjectionConfig>,
1166 pub(crate) override_config: Option<OverrideConfig>,
1167 pub(crate) debug_variables_config: Option<DebugVariablesConfig>,
1168 pub(crate) highlight_map: Mutex<HighlightMap>,
1169}
1170
1171struct IndentConfig {
1172 query: Query,
1173 indent_capture_ix: u32,
1174 start_capture_ix: Option<u32>,
1175 end_capture_ix: Option<u32>,
1176 outdent_capture_ix: Option<u32>,
1177 suffixed_start_captures: HashMap<u32, SharedString>,
1178}
1179
1180pub struct OutlineConfig {
1181 pub query: Query,
1182 pub item_capture_ix: u32,
1183 pub name_capture_ix: u32,
1184 pub context_capture_ix: Option<u32>,
1185 pub extra_context_capture_ix: Option<u32>,
1186 pub open_capture_ix: Option<u32>,
1187 pub close_capture_ix: Option<u32>,
1188 pub annotation_capture_ix: Option<u32>,
1189}
1190
1191#[derive(Debug, Clone, Copy, PartialEq)]
1192pub enum DebuggerTextObject {
1193 Variable,
1194 Scope,
1195}
1196
1197impl DebuggerTextObject {
1198 pub fn from_capture_name(name: &str) -> Option<DebuggerTextObject> {
1199 match name {
1200 "debug-variable" => Some(DebuggerTextObject::Variable),
1201 "debug-scope" => Some(DebuggerTextObject::Scope),
1202 _ => None,
1203 }
1204 }
1205}
1206
1207#[derive(Debug, Clone, Copy, PartialEq)]
1208pub enum TextObject {
1209 InsideFunction,
1210 AroundFunction,
1211 InsideClass,
1212 AroundClass,
1213 InsideComment,
1214 AroundComment,
1215}
1216
1217impl TextObject {
1218 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1219 match name {
1220 "function.inside" => Some(TextObject::InsideFunction),
1221 "function.around" => Some(TextObject::AroundFunction),
1222 "class.inside" => Some(TextObject::InsideClass),
1223 "class.around" => Some(TextObject::AroundClass),
1224 "comment.inside" => Some(TextObject::InsideComment),
1225 "comment.around" => Some(TextObject::AroundComment),
1226 _ => None,
1227 }
1228 }
1229
1230 pub fn around(&self) -> Option<Self> {
1231 match self {
1232 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1233 TextObject::InsideClass => Some(TextObject::AroundClass),
1234 TextObject::InsideComment => Some(TextObject::AroundComment),
1235 _ => None,
1236 }
1237 }
1238}
1239
1240pub struct TextObjectConfig {
1241 pub query: Query,
1242 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1243}
1244
1245#[derive(Debug)]
1246pub struct EmbeddingConfig {
1247 pub query: Query,
1248 pub item_capture_ix: u32,
1249 pub name_capture_ix: Option<u32>,
1250 pub context_capture_ix: Option<u32>,
1251 pub collapse_capture_ix: Option<u32>,
1252 pub keep_capture_ix: Option<u32>,
1253}
1254
1255struct InjectionConfig {
1256 query: Query,
1257 content_capture_ix: u32,
1258 language_capture_ix: Option<u32>,
1259 patterns: Vec<InjectionPatternConfig>,
1260}
1261
1262struct RedactionConfig {
1263 pub query: Query,
1264 pub redaction_capture_ix: u32,
1265}
1266
1267#[derive(Clone, Debug, PartialEq)]
1268enum RunnableCapture {
1269 Named(SharedString),
1270 Run,
1271}
1272
1273struct RunnableConfig {
1274 pub query: Query,
1275 /// A mapping from capture indice to capture kind
1276 pub extra_captures: Vec<RunnableCapture>,
1277}
1278
1279struct OverrideConfig {
1280 query: Query,
1281 values: HashMap<u32, OverrideEntry>,
1282}
1283
1284#[derive(Debug)]
1285struct OverrideEntry {
1286 name: String,
1287 range_is_inclusive: bool,
1288 value: LanguageConfigOverride,
1289}
1290
1291#[derive(Default, Clone)]
1292struct InjectionPatternConfig {
1293 language: Option<Box<str>>,
1294 combined: bool,
1295}
1296
1297#[derive(Debug)]
1298struct BracketsConfig {
1299 query: Query,
1300 open_capture_ix: u32,
1301 close_capture_ix: u32,
1302 patterns: Vec<BracketsPatternConfig>,
1303}
1304
1305#[derive(Clone, Debug, Default)]
1306struct BracketsPatternConfig {
1307 newline_only: bool,
1308}
1309
1310pub struct DebugVariablesConfig {
1311 pub query: Query,
1312 pub objects_by_capture_ix: Vec<(u32, DebuggerTextObject)>,
1313}
1314
1315impl Language {
1316 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1317 Self::new_with_id(LanguageId::new(), config, ts_language)
1318 }
1319
1320 pub fn id(&self) -> LanguageId {
1321 self.id
1322 }
1323
1324 fn new_with_id(
1325 id: LanguageId,
1326 config: LanguageConfig,
1327 ts_language: Option<tree_sitter::Language>,
1328 ) -> Self {
1329 Self {
1330 id,
1331 config,
1332 grammar: ts_language.map(|ts_language| {
1333 Arc::new(Grammar {
1334 id: GrammarId::new(),
1335 highlights_query: None,
1336 brackets_config: None,
1337 outline_config: None,
1338 text_object_config: None,
1339 embedding_config: None,
1340 indents_config: None,
1341 injection_config: None,
1342 override_config: None,
1343 redactions_config: None,
1344 runnable_config: None,
1345 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1346 debug_variables_config: None,
1347 ts_language,
1348 highlight_map: Default::default(),
1349 })
1350 }),
1351 context_provider: None,
1352 toolchain: None,
1353 manifest_name: None,
1354 }
1355 }
1356
1357 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1358 self.context_provider = provider;
1359 self
1360 }
1361
1362 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1363 self.toolchain = provider;
1364 self
1365 }
1366
1367 pub fn with_manifest(mut self, name: Option<ManifestName>) -> Self {
1368 self.manifest_name = name;
1369 self
1370 }
1371 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1372 if let Some(query) = queries.highlights {
1373 self = self
1374 .with_highlights_query(query.as_ref())
1375 .context("Error loading highlights query")?;
1376 }
1377 if let Some(query) = queries.brackets {
1378 self = self
1379 .with_brackets_query(query.as_ref())
1380 .context("Error loading brackets query")?;
1381 }
1382 if let Some(query) = queries.indents {
1383 self = self
1384 .with_indents_query(query.as_ref())
1385 .context("Error loading indents query")?;
1386 }
1387 if let Some(query) = queries.outline {
1388 self = self
1389 .with_outline_query(query.as_ref())
1390 .context("Error loading outline query")?;
1391 }
1392 if let Some(query) = queries.embedding {
1393 self = self
1394 .with_embedding_query(query.as_ref())
1395 .context("Error loading embedding query")?;
1396 }
1397 if let Some(query) = queries.injections {
1398 self = self
1399 .with_injection_query(query.as_ref())
1400 .context("Error loading injection query")?;
1401 }
1402 if let Some(query) = queries.overrides {
1403 self = self
1404 .with_override_query(query.as_ref())
1405 .context("Error loading override query")?;
1406 }
1407 if let Some(query) = queries.redactions {
1408 self = self
1409 .with_redaction_query(query.as_ref())
1410 .context("Error loading redaction query")?;
1411 }
1412 if let Some(query) = queries.runnables {
1413 self = self
1414 .with_runnable_query(query.as_ref())
1415 .context("Error loading runnables query")?;
1416 }
1417 if let Some(query) = queries.text_objects {
1418 self = self
1419 .with_text_object_query(query.as_ref())
1420 .context("Error loading textobject query")?;
1421 }
1422 if let Some(query) = queries.debugger {
1423 self = self
1424 .with_debug_variables_query(query.as_ref())
1425 .context("Error loading debug variables query")?;
1426 }
1427 Ok(self)
1428 }
1429
1430 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1431 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1432 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1433 Ok(self)
1434 }
1435
1436 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1437 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1438
1439 let query = Query::new(&grammar.ts_language, source)?;
1440 let extra_captures: Vec<_> = query
1441 .capture_names()
1442 .iter()
1443 .map(|&name| match name {
1444 "run" => RunnableCapture::Run,
1445 name => RunnableCapture::Named(name.to_string().into()),
1446 })
1447 .collect();
1448
1449 grammar.runnable_config = Some(RunnableConfig {
1450 extra_captures,
1451 query,
1452 });
1453
1454 Ok(self)
1455 }
1456
1457 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1458 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1459 let query = Query::new(&grammar.ts_language, source)?;
1460 let mut item_capture_ix = None;
1461 let mut name_capture_ix = None;
1462 let mut context_capture_ix = None;
1463 let mut extra_context_capture_ix = None;
1464 let mut open_capture_ix = None;
1465 let mut close_capture_ix = None;
1466 let mut annotation_capture_ix = None;
1467 get_capture_indices(
1468 &query,
1469 &mut [
1470 ("item", &mut item_capture_ix),
1471 ("name", &mut name_capture_ix),
1472 ("context", &mut context_capture_ix),
1473 ("context.extra", &mut extra_context_capture_ix),
1474 ("open", &mut open_capture_ix),
1475 ("close", &mut close_capture_ix),
1476 ("annotation", &mut annotation_capture_ix),
1477 ],
1478 );
1479 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1480 grammar.outline_config = Some(OutlineConfig {
1481 query,
1482 item_capture_ix,
1483 name_capture_ix,
1484 context_capture_ix,
1485 extra_context_capture_ix,
1486 open_capture_ix,
1487 close_capture_ix,
1488 annotation_capture_ix,
1489 });
1490 }
1491 Ok(self)
1492 }
1493
1494 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1495 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1496 let query = Query::new(&grammar.ts_language, source)?;
1497
1498 let mut text_objects_by_capture_ix = Vec::new();
1499 for (ix, name) in query.capture_names().iter().enumerate() {
1500 if let Some(text_object) = TextObject::from_capture_name(name) {
1501 text_objects_by_capture_ix.push((ix as u32, text_object));
1502 }
1503 }
1504
1505 grammar.text_object_config = Some(TextObjectConfig {
1506 query,
1507 text_objects_by_capture_ix,
1508 });
1509 Ok(self)
1510 }
1511
1512 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1513 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1514 let query = Query::new(&grammar.ts_language, source)?;
1515 let mut item_capture_ix = None;
1516 let mut name_capture_ix = None;
1517 let mut context_capture_ix = None;
1518 let mut collapse_capture_ix = None;
1519 let mut keep_capture_ix = None;
1520 get_capture_indices(
1521 &query,
1522 &mut [
1523 ("item", &mut item_capture_ix),
1524 ("name", &mut name_capture_ix),
1525 ("context", &mut context_capture_ix),
1526 ("keep", &mut keep_capture_ix),
1527 ("collapse", &mut collapse_capture_ix),
1528 ],
1529 );
1530 if let Some(item_capture_ix) = item_capture_ix {
1531 grammar.embedding_config = Some(EmbeddingConfig {
1532 query,
1533 item_capture_ix,
1534 name_capture_ix,
1535 context_capture_ix,
1536 collapse_capture_ix,
1537 keep_capture_ix,
1538 });
1539 }
1540 Ok(self)
1541 }
1542
1543 pub fn with_debug_variables_query(mut self, source: &str) -> Result<Self> {
1544 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1545 let query = Query::new(&grammar.ts_language, source)?;
1546
1547 let mut objects_by_capture_ix = Vec::new();
1548 for (ix, name) in query.capture_names().iter().enumerate() {
1549 if let Some(text_object) = DebuggerTextObject::from_capture_name(name) {
1550 objects_by_capture_ix.push((ix as u32, text_object));
1551 }
1552 }
1553
1554 grammar.debug_variables_config = Some(DebugVariablesConfig {
1555 query,
1556 objects_by_capture_ix,
1557 });
1558 Ok(self)
1559 }
1560
1561 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1562 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1563 let query = Query::new(&grammar.ts_language, source)?;
1564 let mut open_capture_ix = None;
1565 let mut close_capture_ix = None;
1566 get_capture_indices(
1567 &query,
1568 &mut [
1569 ("open", &mut open_capture_ix),
1570 ("close", &mut close_capture_ix),
1571 ],
1572 );
1573 let patterns = (0..query.pattern_count())
1574 .map(|ix| {
1575 let mut config = BracketsPatternConfig::default();
1576 for setting in query.property_settings(ix) {
1577 if setting.key.as_ref() == "newline.only" {
1578 config.newline_only = true
1579 }
1580 }
1581 config
1582 })
1583 .collect();
1584 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1585 grammar.brackets_config = Some(BracketsConfig {
1586 query,
1587 open_capture_ix,
1588 close_capture_ix,
1589 patterns,
1590 });
1591 }
1592 Ok(self)
1593 }
1594
1595 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1596 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1597 let query = Query::new(&grammar.ts_language, source)?;
1598 let mut indent_capture_ix = None;
1599 let mut start_capture_ix = None;
1600 let mut end_capture_ix = None;
1601 let mut outdent_capture_ix = None;
1602 get_capture_indices(
1603 &query,
1604 &mut [
1605 ("indent", &mut indent_capture_ix),
1606 ("start", &mut start_capture_ix),
1607 ("end", &mut end_capture_ix),
1608 ("outdent", &mut outdent_capture_ix),
1609 ],
1610 );
1611
1612 let mut suffixed_start_captures = HashMap::default();
1613 for (ix, name) in query.capture_names().iter().enumerate() {
1614 if let Some(suffix) = name.strip_prefix("start.") {
1615 suffixed_start_captures.insert(ix as u32, suffix.to_owned().into());
1616 }
1617 }
1618
1619 if let Some(indent_capture_ix) = indent_capture_ix {
1620 grammar.indents_config = Some(IndentConfig {
1621 query,
1622 indent_capture_ix,
1623 start_capture_ix,
1624 end_capture_ix,
1625 outdent_capture_ix,
1626 suffixed_start_captures,
1627 });
1628 }
1629 Ok(self)
1630 }
1631
1632 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1633 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1634 let query = Query::new(&grammar.ts_language, source)?;
1635 let mut language_capture_ix = None;
1636 let mut injection_language_capture_ix = None;
1637 let mut content_capture_ix = None;
1638 let mut injection_content_capture_ix = None;
1639 get_capture_indices(
1640 &query,
1641 &mut [
1642 ("language", &mut language_capture_ix),
1643 ("injection.language", &mut injection_language_capture_ix),
1644 ("content", &mut content_capture_ix),
1645 ("injection.content", &mut injection_content_capture_ix),
1646 ],
1647 );
1648 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1649 (None, Some(ix)) => Some(ix),
1650 (Some(_), Some(_)) => {
1651 anyhow::bail!("both language and injection.language captures are present");
1652 }
1653 _ => language_capture_ix,
1654 };
1655 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1656 (None, Some(ix)) => Some(ix),
1657 (Some(_), Some(_)) => {
1658 anyhow::bail!("both content and injection.content captures are present")
1659 }
1660 _ => content_capture_ix,
1661 };
1662 let patterns = (0..query.pattern_count())
1663 .map(|ix| {
1664 let mut config = InjectionPatternConfig::default();
1665 for setting in query.property_settings(ix) {
1666 match setting.key.as_ref() {
1667 "language" | "injection.language" => {
1668 config.language.clone_from(&setting.value);
1669 }
1670 "combined" | "injection.combined" => {
1671 config.combined = true;
1672 }
1673 _ => {}
1674 }
1675 }
1676 config
1677 })
1678 .collect();
1679 if let Some(content_capture_ix) = content_capture_ix {
1680 grammar.injection_config = Some(InjectionConfig {
1681 query,
1682 language_capture_ix,
1683 content_capture_ix,
1684 patterns,
1685 });
1686 }
1687 Ok(self)
1688 }
1689
1690 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1691 let query = {
1692 let grammar = self.grammar.as_ref().context("no grammar for language")?;
1693 Query::new(&grammar.ts_language, source)?
1694 };
1695
1696 let mut override_configs_by_id = HashMap::default();
1697 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1698 let mut range_is_inclusive = false;
1699 if name.starts_with('_') {
1700 continue;
1701 }
1702 if let Some(prefix) = name.strip_suffix(".inclusive") {
1703 name = prefix;
1704 range_is_inclusive = true;
1705 }
1706
1707 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1708 for server_name in &value.opt_into_language_servers {
1709 if !self
1710 .config
1711 .scope_opt_in_language_servers
1712 .contains(server_name)
1713 {
1714 util::debug_panic!(
1715 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1716 );
1717 }
1718 }
1719
1720 override_configs_by_id.insert(
1721 ix as u32,
1722 OverrideEntry {
1723 name: name.to_string(),
1724 range_is_inclusive,
1725 value,
1726 },
1727 );
1728 }
1729
1730 let referenced_override_names = self.config.overrides.keys().chain(
1731 self.config
1732 .brackets
1733 .disabled_scopes_by_bracket_ix
1734 .iter()
1735 .flatten(),
1736 );
1737
1738 for referenced_name in referenced_override_names {
1739 if !override_configs_by_id
1740 .values()
1741 .any(|entry| entry.name == *referenced_name)
1742 {
1743 anyhow::bail!(
1744 "language {:?} has overrides in config not in query: {referenced_name:?}",
1745 self.config.name
1746 );
1747 }
1748 }
1749
1750 for entry in override_configs_by_id.values_mut() {
1751 entry.value.disabled_bracket_ixs = self
1752 .config
1753 .brackets
1754 .disabled_scopes_by_bracket_ix
1755 .iter()
1756 .enumerate()
1757 .filter_map(|(ix, disabled_scope_names)| {
1758 if disabled_scope_names.contains(&entry.name) {
1759 Some(ix as u16)
1760 } else {
1761 None
1762 }
1763 })
1764 .collect();
1765 }
1766
1767 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1768
1769 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1770 grammar.override_config = Some(OverrideConfig {
1771 query,
1772 values: override_configs_by_id,
1773 });
1774 Ok(self)
1775 }
1776
1777 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1778 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1779
1780 let query = Query::new(&grammar.ts_language, source)?;
1781 let mut redaction_capture_ix = None;
1782 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1783
1784 if let Some(redaction_capture_ix) = redaction_capture_ix {
1785 grammar.redactions_config = Some(RedactionConfig {
1786 query,
1787 redaction_capture_ix,
1788 });
1789 }
1790
1791 Ok(self)
1792 }
1793
1794 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1795 Arc::get_mut(self.grammar.as_mut()?)
1796 }
1797
1798 pub fn name(&self) -> LanguageName {
1799 self.config.name.clone()
1800 }
1801 pub fn manifest(&self) -> Option<&ManifestName> {
1802 self.manifest_name.as_ref()
1803 }
1804
1805 pub fn code_fence_block_name(&self) -> Arc<str> {
1806 self.config
1807 .code_fence_block_name
1808 .clone()
1809 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1810 }
1811
1812 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1813 self.context_provider.clone()
1814 }
1815
1816 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1817 self.toolchain.clone()
1818 }
1819
1820 pub fn highlight_text<'a>(
1821 self: &'a Arc<Self>,
1822 text: &'a Rope,
1823 range: Range<usize>,
1824 ) -> Vec<(Range<usize>, HighlightId)> {
1825 let mut result = Vec::new();
1826 if let Some(grammar) = &self.grammar {
1827 let tree = grammar.parse_text(text, None);
1828 let captures =
1829 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1830 grammar.highlights_query.as_ref()
1831 });
1832 let highlight_maps = vec![grammar.highlight_map()];
1833 let mut offset = 0;
1834 for chunk in
1835 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1836 {
1837 let end_offset = offset + chunk.text.len();
1838 if let Some(highlight_id) = chunk.syntax_highlight_id
1839 && !highlight_id.is_default()
1840 {
1841 result.push((offset..end_offset, highlight_id));
1842 }
1843 offset = end_offset;
1844 }
1845 }
1846 result
1847 }
1848
1849 pub fn path_suffixes(&self) -> &[String] {
1850 &self.config.matcher.path_suffixes
1851 }
1852
1853 pub fn should_autoclose_before(&self, c: char) -> bool {
1854 c.is_whitespace() || self.config.autoclose_before.contains(c)
1855 }
1856
1857 pub fn set_theme(&self, theme: &SyntaxTheme) {
1858 if let Some(grammar) = self.grammar.as_ref()
1859 && let Some(highlights_query) = &grammar.highlights_query
1860 {
1861 *grammar.highlight_map.lock() =
1862 HighlightMap::new(highlights_query.capture_names(), theme);
1863 }
1864 }
1865
1866 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1867 self.grammar.as_ref()
1868 }
1869
1870 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1871 LanguageScope {
1872 language: self.clone(),
1873 override_id: None,
1874 }
1875 }
1876
1877 pub fn lsp_id(&self) -> String {
1878 self.config.name.lsp_id()
1879 }
1880
1881 pub fn prettier_parser_name(&self) -> Option<&str> {
1882 self.config.prettier_parser_name.as_deref()
1883 }
1884
1885 pub fn config(&self) -> &LanguageConfig {
1886 &self.config
1887 }
1888}
1889
1890impl LanguageScope {
1891 pub fn path_suffixes(&self) -> &[String] {
1892 self.language.path_suffixes()
1893 }
1894
1895 pub fn language_name(&self) -> LanguageName {
1896 self.language.config.name.clone()
1897 }
1898
1899 pub fn collapsed_placeholder(&self) -> &str {
1900 self.language.config.collapsed_placeholder.as_ref()
1901 }
1902
1903 /// Returns line prefix that is inserted in e.g. line continuations or
1904 /// in `toggle comments` action.
1905 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1906 Override::as_option(
1907 self.config_override().map(|o| &o.line_comments),
1908 Some(&self.language.config.line_comments),
1909 )
1910 .map_or([].as_slice(), |e| e.as_slice())
1911 }
1912
1913 /// Config for block comments for this language.
1914 pub fn block_comment(&self) -> Option<&BlockCommentConfig> {
1915 Override::as_option(
1916 self.config_override().map(|o| &o.block_comment),
1917 self.language.config.block_comment.as_ref(),
1918 )
1919 }
1920
1921 /// Config for documentation-style block comments for this language.
1922 pub fn documentation_comment(&self) -> Option<&BlockCommentConfig> {
1923 self.language.config.documentation_comment.as_ref()
1924 }
1925
1926 /// Returns additional regex patterns that act as prefix markers for creating
1927 /// boundaries during rewrapping.
1928 ///
1929 /// By default, Zed treats as paragraph and comment prefixes as boundaries.
1930 pub fn rewrap_prefixes(&self) -> &[Regex] {
1931 &self.language.config.rewrap_prefixes
1932 }
1933
1934 /// Returns a list of language-specific word characters.
1935 ///
1936 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1937 /// the purpose of actions like 'move to next word end` or whole-word search.
1938 /// It additionally accounts for language's additional word characters.
1939 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1940 Override::as_option(
1941 self.config_override().map(|o| &o.word_characters),
1942 Some(&self.language.config.word_characters),
1943 )
1944 }
1945
1946 /// Returns a list of language-specific characters that are considered part of
1947 /// a completion query.
1948 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1949 Override::as_option(
1950 self.config_override()
1951 .map(|o| &o.completion_query_characters),
1952 Some(&self.language.config.completion_query_characters),
1953 )
1954 }
1955
1956 /// Returns whether to prefer snippet `label` over `new_text` to replace text when
1957 /// completion is accepted.
1958 ///
1959 /// In cases like when cursor is in string or renaming existing function,
1960 /// you don't want to expand function signature instead just want function name
1961 /// to replace existing one.
1962 pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
1963 self.config_override()
1964 .and_then(|o| o.prefer_label_for_snippet)
1965 .unwrap_or(false)
1966 }
1967
1968 /// Returns a list of bracket pairs for a given language with an additional
1969 /// piece of information about whether the particular bracket pair is currently active for a given language.
1970 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1971 let mut disabled_ids = self
1972 .config_override()
1973 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1974 self.language
1975 .config
1976 .brackets
1977 .pairs
1978 .iter()
1979 .enumerate()
1980 .map(move |(ix, bracket)| {
1981 let mut is_enabled = true;
1982 if let Some(next_disabled_ix) = disabled_ids.first()
1983 && ix == *next_disabled_ix as usize
1984 {
1985 disabled_ids = &disabled_ids[1..];
1986 is_enabled = false;
1987 }
1988 (bracket, is_enabled)
1989 })
1990 }
1991
1992 pub fn should_autoclose_before(&self, c: char) -> bool {
1993 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1994 }
1995
1996 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1997 let config = &self.language.config;
1998 let opt_in_servers = &config.scope_opt_in_language_servers;
1999 if opt_in_servers.contains(name) {
2000 if let Some(over) = self.config_override() {
2001 over.opt_into_language_servers.contains(name)
2002 } else {
2003 false
2004 }
2005 } else {
2006 true
2007 }
2008 }
2009
2010 pub fn override_name(&self) -> Option<&str> {
2011 let id = self.override_id?;
2012 let grammar = self.language.grammar.as_ref()?;
2013 let override_config = grammar.override_config.as_ref()?;
2014 override_config.values.get(&id).map(|e| e.name.as_str())
2015 }
2016
2017 fn config_override(&self) -> Option<&LanguageConfigOverride> {
2018 let id = self.override_id?;
2019 let grammar = self.language.grammar.as_ref()?;
2020 let override_config = grammar.override_config.as_ref()?;
2021 override_config.values.get(&id).map(|e| &e.value)
2022 }
2023}
2024
2025impl Hash for Language {
2026 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2027 self.id.hash(state)
2028 }
2029}
2030
2031impl PartialEq for Language {
2032 fn eq(&self, other: &Self) -> bool {
2033 self.id.eq(&other.id)
2034 }
2035}
2036
2037impl Eq for Language {}
2038
2039impl Debug for Language {
2040 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2041 f.debug_struct("Language")
2042 .field("name", &self.config.name)
2043 .finish()
2044 }
2045}
2046
2047impl Grammar {
2048 pub fn id(&self) -> GrammarId {
2049 self.id
2050 }
2051
2052 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
2053 with_parser(|parser| {
2054 parser
2055 .set_language(&self.ts_language)
2056 .expect("incompatible grammar");
2057 let mut chunks = text.chunks_in_range(0..text.len());
2058 parser
2059 .parse_with_options(
2060 &mut move |offset, _| {
2061 chunks.seek(offset);
2062 chunks.next().unwrap_or("").as_bytes()
2063 },
2064 old_tree.as_ref(),
2065 None,
2066 )
2067 .unwrap()
2068 })
2069 }
2070
2071 pub fn highlight_map(&self) -> HighlightMap {
2072 self.highlight_map.lock().clone()
2073 }
2074
2075 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
2076 let capture_id = self
2077 .highlights_query
2078 .as_ref()?
2079 .capture_index_for_name(name)?;
2080 Some(self.highlight_map.lock().get(capture_id))
2081 }
2082
2083 pub fn debug_variables_config(&self) -> Option<&DebugVariablesConfig> {
2084 self.debug_variables_config.as_ref()
2085 }
2086}
2087
2088impl CodeLabel {
2089 pub fn fallback_for_completion(
2090 item: &lsp::CompletionItem,
2091 language: Option<&Language>,
2092 ) -> Self {
2093 let highlight_id = item.kind.and_then(|kind| {
2094 let grammar = language?.grammar()?;
2095 use lsp::CompletionItemKind as Kind;
2096 match kind {
2097 Kind::CLASS => grammar.highlight_id_for_name("type"),
2098 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
2099 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
2100 Kind::ENUM => grammar
2101 .highlight_id_for_name("enum")
2102 .or_else(|| grammar.highlight_id_for_name("type")),
2103 Kind::ENUM_MEMBER => grammar
2104 .highlight_id_for_name("variant")
2105 .or_else(|| grammar.highlight_id_for_name("property")),
2106 Kind::FIELD => grammar.highlight_id_for_name("property"),
2107 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
2108 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
2109 Kind::METHOD => grammar
2110 .highlight_id_for_name("function.method")
2111 .or_else(|| grammar.highlight_id_for_name("function")),
2112 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
2113 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
2114 Kind::STRUCT => grammar.highlight_id_for_name("type"),
2115 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
2116 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
2117 _ => None,
2118 }
2119 });
2120
2121 let label = &item.label;
2122 let label_length = label.len();
2123 let runs = highlight_id
2124 .map(|highlight_id| vec![(0..label_length, highlight_id)])
2125 .unwrap_or_default();
2126 let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
2127 format!("{label} {detail}")
2128 } else if let Some(description) = item
2129 .label_details
2130 .as_ref()
2131 .and_then(|label_details| label_details.description.as_deref())
2132 .filter(|description| description != label)
2133 {
2134 format!("{label} {description}")
2135 } else {
2136 label.clone()
2137 };
2138 let filter_range = item
2139 .filter_text
2140 .as_deref()
2141 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2142 .unwrap_or(0..label_length);
2143 Self {
2144 text,
2145 runs,
2146 filter_range,
2147 }
2148 }
2149
2150 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
2151 let filter_range = filter_text
2152 .and_then(|filter| text.find(filter).map(|ix| ix..ix + filter.len()))
2153 .unwrap_or(0..text.len());
2154 Self {
2155 runs: Vec::new(),
2156 filter_range,
2157 text,
2158 }
2159 }
2160
2161 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2162 let start_ix = self.text.len();
2163 self.text.push_str(text);
2164 let end_ix = self.text.len();
2165 if let Some(highlight) = highlight {
2166 self.runs.push((start_ix..end_ix, highlight));
2167 }
2168 }
2169
2170 pub fn text(&self) -> &str {
2171 self.text.as_str()
2172 }
2173
2174 pub fn filter_text(&self) -> &str {
2175 &self.text[self.filter_range.clone()]
2176 }
2177}
2178
2179impl From<String> for CodeLabel {
2180 fn from(value: String) -> Self {
2181 Self::plain(value, None)
2182 }
2183}
2184
2185impl From<&str> for CodeLabel {
2186 fn from(value: &str) -> Self {
2187 Self::plain(value.to_string(), None)
2188 }
2189}
2190
2191impl Ord for LanguageMatcher {
2192 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2193 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2194 self.first_line_pattern
2195 .as_ref()
2196 .map(Regex::as_str)
2197 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2198 })
2199 }
2200}
2201
2202impl PartialOrd for LanguageMatcher {
2203 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2204 Some(self.cmp(other))
2205 }
2206}
2207
2208impl Eq for LanguageMatcher {}
2209
2210impl PartialEq for LanguageMatcher {
2211 fn eq(&self, other: &Self) -> bool {
2212 self.path_suffixes == other.path_suffixes
2213 && self.first_line_pattern.as_ref().map(Regex::as_str)
2214 == other.first_line_pattern.as_ref().map(Regex::as_str)
2215 }
2216}
2217
2218#[cfg(any(test, feature = "test-support"))]
2219impl Default for FakeLspAdapter {
2220 fn default() -> Self {
2221 Self {
2222 name: "the-fake-language-server",
2223 capabilities: lsp::LanguageServer::full_capabilities(),
2224 initializer: None,
2225 disk_based_diagnostics_progress_token: None,
2226 initialization_options: None,
2227 disk_based_diagnostics_sources: Vec::new(),
2228 prettier_plugins: Vec::new(),
2229 language_server_binary: LanguageServerBinary {
2230 path: "/the/fake/lsp/path".into(),
2231 arguments: vec![],
2232 env: Default::default(),
2233 },
2234 label_for_completion: None,
2235 }
2236 }
2237}
2238
2239#[cfg(any(test, feature = "test-support"))]
2240impl LspInstaller for FakeLspAdapter {
2241 type BinaryVersion = ();
2242
2243 async fn fetch_latest_server_version(
2244 &self,
2245 _: &dyn LspAdapterDelegate,
2246 _: bool,
2247 _: &mut AsyncApp,
2248 ) -> Result<Self::BinaryVersion> {
2249 unreachable!()
2250 }
2251
2252 async fn check_if_user_installed(
2253 &self,
2254 _: &dyn LspAdapterDelegate,
2255 _: Option<Toolchain>,
2256 _: &AsyncApp,
2257 ) -> Option<LanguageServerBinary> {
2258 Some(self.language_server_binary.clone())
2259 }
2260
2261 async fn fetch_server_binary(
2262 &self,
2263 _: (),
2264 _: PathBuf,
2265 _: &dyn LspAdapterDelegate,
2266 ) -> Result<LanguageServerBinary> {
2267 unreachable!();
2268 }
2269
2270 async fn cached_server_binary(
2271 &self,
2272 _: PathBuf,
2273 _: &dyn LspAdapterDelegate,
2274 ) -> Option<LanguageServerBinary> {
2275 unreachable!();
2276 }
2277}
2278
2279#[cfg(any(test, feature = "test-support"))]
2280#[async_trait(?Send)]
2281impl LspAdapter for FakeLspAdapter {
2282 fn name(&self) -> LanguageServerName {
2283 LanguageServerName(self.name.into())
2284 }
2285
2286 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2287 self.disk_based_diagnostics_sources.clone()
2288 }
2289
2290 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2291 self.disk_based_diagnostics_progress_token.clone()
2292 }
2293
2294 async fn initialization_options(
2295 self: Arc<Self>,
2296 _: &Arc<dyn LspAdapterDelegate>,
2297 ) -> Result<Option<Value>> {
2298 Ok(self.initialization_options.clone())
2299 }
2300
2301 async fn label_for_completion(
2302 &self,
2303 item: &lsp::CompletionItem,
2304 language: &Arc<Language>,
2305 ) -> Option<CodeLabel> {
2306 let label_for_completion = self.label_for_completion.as_ref()?;
2307 label_for_completion(item, language)
2308 }
2309
2310 fn is_extension(&self) -> bool {
2311 false
2312 }
2313}
2314
2315fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2316 for (ix, name) in query.capture_names().iter().enumerate() {
2317 for (capture_name, index) in captures.iter_mut() {
2318 if capture_name == name {
2319 **index = Some(ix as u32);
2320 break;
2321 }
2322 }
2323 }
2324}
2325
2326pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2327 lsp::Position::new(point.row, point.column)
2328}
2329
2330pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2331 Unclipped(PointUtf16::new(point.line, point.character))
2332}
2333
2334pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2335 anyhow::ensure!(
2336 range.start <= range.end,
2337 "Inverted range provided to an LSP request: {:?}-{:?}",
2338 range.start,
2339 range.end
2340 );
2341 Ok(lsp::Range {
2342 start: point_to_lsp(range.start),
2343 end: point_to_lsp(range.end),
2344 })
2345}
2346
2347pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2348 let mut start = point_from_lsp(range.start);
2349 let mut end = point_from_lsp(range.end);
2350 if start > end {
2351 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2352 mem::swap(&mut start, &mut end);
2353 }
2354 start..end
2355}
2356
2357#[cfg(test)]
2358mod tests {
2359 use super::*;
2360 use gpui::TestAppContext;
2361 use pretty_assertions::assert_matches;
2362
2363 #[gpui::test(iterations = 10)]
2364 async fn test_language_loading(cx: &mut TestAppContext) {
2365 let languages = LanguageRegistry::test(cx.executor());
2366 let languages = Arc::new(languages);
2367 languages.register_native_grammars([
2368 ("json", tree_sitter_json::LANGUAGE),
2369 ("rust", tree_sitter_rust::LANGUAGE),
2370 ]);
2371 languages.register_test_language(LanguageConfig {
2372 name: "JSON".into(),
2373 grammar: Some("json".into()),
2374 matcher: LanguageMatcher {
2375 path_suffixes: vec!["json".into()],
2376 ..Default::default()
2377 },
2378 ..Default::default()
2379 });
2380 languages.register_test_language(LanguageConfig {
2381 name: "Rust".into(),
2382 grammar: Some("rust".into()),
2383 matcher: LanguageMatcher {
2384 path_suffixes: vec!["rs".into()],
2385 ..Default::default()
2386 },
2387 ..Default::default()
2388 });
2389 assert_eq!(
2390 languages.language_names(),
2391 &[
2392 LanguageName::new("JSON"),
2393 LanguageName::new("Plain Text"),
2394 LanguageName::new("Rust"),
2395 ]
2396 );
2397
2398 let rust1 = languages.language_for_name("Rust");
2399 let rust2 = languages.language_for_name("Rust");
2400
2401 // Ensure language is still listed even if it's being loaded.
2402 assert_eq!(
2403 languages.language_names(),
2404 &[
2405 LanguageName::new("JSON"),
2406 LanguageName::new("Plain Text"),
2407 LanguageName::new("Rust"),
2408 ]
2409 );
2410
2411 let (rust1, rust2) = futures::join!(rust1, rust2);
2412 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2413
2414 // Ensure language is still listed even after loading it.
2415 assert_eq!(
2416 languages.language_names(),
2417 &[
2418 LanguageName::new("JSON"),
2419 LanguageName::new("Plain Text"),
2420 LanguageName::new("Rust"),
2421 ]
2422 );
2423
2424 // Loading an unknown language returns an error.
2425 assert!(languages.language_for_name("Unknown").await.is_err());
2426 }
2427
2428 #[gpui::test]
2429 async fn test_completion_label_omits_duplicate_data() {
2430 let regular_completion_item_1 = lsp::CompletionItem {
2431 label: "regular1".to_string(),
2432 detail: Some("detail1".to_string()),
2433 label_details: Some(lsp::CompletionItemLabelDetails {
2434 detail: None,
2435 description: Some("description 1".to_string()),
2436 }),
2437 ..lsp::CompletionItem::default()
2438 };
2439
2440 let regular_completion_item_2 = lsp::CompletionItem {
2441 label: "regular2".to_string(),
2442 label_details: Some(lsp::CompletionItemLabelDetails {
2443 detail: None,
2444 description: Some("description 2".to_string()),
2445 }),
2446 ..lsp::CompletionItem::default()
2447 };
2448
2449 let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2450 detail: Some(regular_completion_item_1.label.clone()),
2451 ..regular_completion_item_1.clone()
2452 };
2453
2454 let completion_item_with_duplicate_detail = lsp::CompletionItem {
2455 detail: Some(regular_completion_item_1.label.clone()),
2456 label_details: None,
2457 ..regular_completion_item_1.clone()
2458 };
2459
2460 let completion_item_with_duplicate_description = lsp::CompletionItem {
2461 label_details: Some(lsp::CompletionItemLabelDetails {
2462 detail: None,
2463 description: Some(regular_completion_item_2.label.clone()),
2464 }),
2465 ..regular_completion_item_2.clone()
2466 };
2467
2468 assert_eq!(
2469 CodeLabel::fallback_for_completion(®ular_completion_item_1, None).text,
2470 format!(
2471 "{} {}",
2472 regular_completion_item_1.label,
2473 regular_completion_item_1.detail.unwrap()
2474 ),
2475 "LSP completion items with both detail and label_details.description should prefer detail"
2476 );
2477 assert_eq!(
2478 CodeLabel::fallback_for_completion(®ular_completion_item_2, None).text,
2479 format!(
2480 "{} {}",
2481 regular_completion_item_2.label,
2482 regular_completion_item_2
2483 .label_details
2484 .as_ref()
2485 .unwrap()
2486 .description
2487 .as_ref()
2488 .unwrap()
2489 ),
2490 "LSP completion items without detail but with label_details.description should use that"
2491 );
2492 assert_eq!(
2493 CodeLabel::fallback_for_completion(
2494 &completion_item_with_duplicate_detail_and_proper_description,
2495 None
2496 )
2497 .text,
2498 format!(
2499 "{} {}",
2500 regular_completion_item_1.label,
2501 regular_completion_item_1
2502 .label_details
2503 .as_ref()
2504 .unwrap()
2505 .description
2506 .as_ref()
2507 .unwrap()
2508 ),
2509 "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2510 );
2511 assert_eq!(
2512 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2513 regular_completion_item_1.label,
2514 "LSP completion items with duplicate label and detail, should omit the detail"
2515 );
2516 assert_eq!(
2517 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2518 .text,
2519 regular_completion_item_2.label,
2520 "LSP completion items with duplicate label and detail, should omit the detail"
2521 );
2522 }
2523
2524 #[test]
2525 fn test_deserializing_comments_backwards_compat() {
2526 // current version of `block_comment` and `documentation_comment` work
2527 {
2528 let config: LanguageConfig = ::toml::from_str(
2529 r#"
2530 name = "Foo"
2531 block_comment = { start = "a", end = "b", prefix = "c", tab_size = 1 }
2532 documentation_comment = { start = "d", end = "e", prefix = "f", tab_size = 2 }
2533 "#,
2534 )
2535 .unwrap();
2536 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2537 assert_matches!(
2538 config.documentation_comment,
2539 Some(BlockCommentConfig { .. })
2540 );
2541
2542 let block_config = config.block_comment.unwrap();
2543 assert_eq!(block_config.start.as_ref(), "a");
2544 assert_eq!(block_config.end.as_ref(), "b");
2545 assert_eq!(block_config.prefix.as_ref(), "c");
2546 assert_eq!(block_config.tab_size, 1);
2547
2548 let doc_config = config.documentation_comment.unwrap();
2549 assert_eq!(doc_config.start.as_ref(), "d");
2550 assert_eq!(doc_config.end.as_ref(), "e");
2551 assert_eq!(doc_config.prefix.as_ref(), "f");
2552 assert_eq!(doc_config.tab_size, 2);
2553 }
2554
2555 // former `documentation` setting is read into `documentation_comment`
2556 {
2557 let config: LanguageConfig = ::toml::from_str(
2558 r#"
2559 name = "Foo"
2560 documentation = { start = "a", end = "b", prefix = "c", tab_size = 1}
2561 "#,
2562 )
2563 .unwrap();
2564 assert_matches!(
2565 config.documentation_comment,
2566 Some(BlockCommentConfig { .. })
2567 );
2568
2569 let config = config.documentation_comment.unwrap();
2570 assert_eq!(config.start.as_ref(), "a");
2571 assert_eq!(config.end.as_ref(), "b");
2572 assert_eq!(config.prefix.as_ref(), "c");
2573 assert_eq!(config.tab_size, 1);
2574 }
2575
2576 // old block_comment format is read into BlockCommentConfig
2577 {
2578 let config: LanguageConfig = ::toml::from_str(
2579 r#"
2580 name = "Foo"
2581 block_comment = ["a", "b"]
2582 "#,
2583 )
2584 .unwrap();
2585 assert_matches!(config.block_comment, Some(BlockCommentConfig { .. }));
2586
2587 let config = config.block_comment.unwrap();
2588 assert_eq!(config.start.as_ref(), "a");
2589 assert_eq!(config.end.as_ref(), "b");
2590 assert_eq!(config.prefix.as_ref(), "");
2591 assert_eq!(config.tab_size, 0);
2592 }
2593 }
2594}