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