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