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