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