1//! The `language` crate provides a large chunk of Zed's language-related
2//! features (the other big contributors being project and lsp crates that revolve around LSP features).
3//! Namely, this crate:
4//! - Provides [`Language`], [`Grammar`] and [`LanguageRegistry`] types that
5//! use Tree-sitter to provide syntax highlighting to the editor; note though that `language` doesn't perform the highlighting by itself. It only maps ranges in a buffer to colors. Treesitter is also used for buffer outlines (lists of symbols in a buffer)
6//! - Exposes [`LanguageConfig`] that describes how constructs (like brackets or line comments) should be handled by the editor for a source file of a particular language.
7//!
8//! Notably we do *not* assign a single language to a single file; in real world a single file can consist of multiple programming languages - HTML is a good example of that - and `language` crate tends to reflect that status quo in its API.
9mod buffer;
10mod diagnostic_set;
11mod highlight_map;
12mod language_registry;
13pub mod language_settings;
14mod manifest;
15mod outline;
16pub mod proto;
17mod syntax_map;
18mod task_context;
19mod text_diff;
20mod toolchain;
21
22#[cfg(test)]
23pub mod buffer_tests;
24
25pub use crate::language_settings::EditPredictionsMode;
26use crate::language_settings::SoftWrap;
27use anyhow::{Context as _, Result};
28use async_trait::async_trait;
29use collections::{HashMap, HashSet, IndexSet};
30use fs::Fs;
31use futures::Future;
32use gpui::{App, AsyncApp, Entity, SharedString, Task};
33pub use highlight_map::HighlightMap;
34use http_client::HttpClient;
35pub use language_registry::{LanguageName, LoadedLanguage};
36use lsp::{CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
37pub use manifest::{ManifestDelegate, ManifestName, ManifestProvider, ManifestQuery};
38use parking_lot::Mutex;
39use regex::Regex;
40use schemars::{
41 JsonSchema,
42 r#gen::SchemaGenerator,
43 schema::{InstanceType, Schema, SchemaObject},
44};
45use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
46use serde_json::Value;
47use settings::WorktreeId;
48use smol::future::FutureExt as _;
49use std::{
50 any::Any,
51 ffi::OsStr,
52 fmt::Debug,
53 hash::Hash,
54 mem,
55 ops::{DerefMut, Range},
56 path::{Path, PathBuf},
57 pin::Pin,
58 str,
59 sync::{
60 Arc, LazyLock,
61 atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
62 },
63};
64use std::{num::NonZeroU32, sync::OnceLock};
65use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
66use task::RunnableTag;
67pub use task_context::{ContextLocation, ContextProvider, RunnableRange};
68pub use text_diff::{
69 DiffOptions, apply_diff_patch, line_diff, text_diff, text_diff_with_options, unified_diff,
70};
71use theme::SyntaxTheme;
72pub use toolchain::{LanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister};
73use tree_sitter::{self, Query, QueryCursor, WasmStore, wasmtime};
74use util::serde::default_true;
75
76pub use buffer::Operation;
77pub use buffer::*;
78pub use diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
79pub use language_registry::{
80 AvailableLanguage, BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry,
81 QUERY_FILENAME_PREFIXES,
82};
83pub use lsp::{LanguageServerId, LanguageServerName};
84pub use outline::*;
85pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer, ToTreeSitterPoint, TreeSitterOptions};
86pub use text::{AnchorRangeExt, LineEnding};
87pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
88
89/// Initializes the `language` crate.
90///
91/// This should be called before making use of items from the create.
92pub fn init(cx: &mut App) {
93 language_settings::init(cx);
94}
95
96static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
97static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
98
99pub fn with_parser<F, R>(func: F) -> R
100where
101 F: FnOnce(&mut Parser) -> R,
102{
103 let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
104 let mut parser = Parser::new();
105 parser
106 .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
107 .unwrap();
108 parser
109 });
110 parser.set_included_ranges(&[]).unwrap();
111 let result = func(&mut parser);
112 PARSERS.lock().push(parser);
113 result
114}
115
116pub fn with_query_cursor<F, R>(func: F) -> R
117where
118 F: FnOnce(&mut QueryCursor) -> R,
119{
120 let mut cursor = QueryCursorHandle::new();
121 func(cursor.deref_mut())
122}
123
124static NEXT_LANGUAGE_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
125static NEXT_GRAMMAR_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
126static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
127 wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
128});
129
130/// A shared grammar for plain text, exposed for reuse by downstream crates.
131pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
132 Arc::new(Language::new(
133 LanguageConfig {
134 name: "Plain Text".into(),
135 soft_wrap: Some(SoftWrap::EditorWidth),
136 matcher: LanguageMatcher {
137 path_suffixes: vec!["txt".to_owned()],
138 first_line_pattern: None,
139 },
140 ..Default::default()
141 },
142 None,
143 ))
144});
145
146/// Types that represent a position in a buffer, and can be converted into
147/// an LSP position, to send to a language server.
148pub trait ToLspPosition {
149 /// Converts the value into an LSP position.
150 fn to_lsp_position(self) -> lsp::Position;
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Hash)]
154pub struct Location {
155 pub buffer: Entity<Buffer>,
156 pub range: Range<Anchor>,
157}
158
159/// Represents a Language Server, with certain cached sync properties.
160/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
161/// once at startup, and caches the results.
162pub struct CachedLspAdapter {
163 pub name: LanguageServerName,
164 pub disk_based_diagnostic_sources: Vec<String>,
165 pub disk_based_diagnostics_progress_token: Option<String>,
166 language_ids: HashMap<String, String>,
167 pub adapter: Arc<dyn LspAdapter>,
168 pub reinstall_attempt_count: AtomicU64,
169 cached_binary: futures::lock::Mutex<Option<LanguageServerBinary>>,
170 manifest_name: OnceLock<Option<ManifestName>>,
171 attach_kind: OnceLock<Attach>,
172}
173
174impl Debug for CachedLspAdapter {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 f.debug_struct("CachedLspAdapter")
177 .field("name", &self.name)
178 .field(
179 "disk_based_diagnostic_sources",
180 &self.disk_based_diagnostic_sources,
181 )
182 .field(
183 "disk_based_diagnostics_progress_token",
184 &self.disk_based_diagnostics_progress_token,
185 )
186 .field("language_ids", &self.language_ids)
187 .field("reinstall_attempt_count", &self.reinstall_attempt_count)
188 .finish_non_exhaustive()
189 }
190}
191
192impl CachedLspAdapter {
193 pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
194 let name = adapter.name();
195 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
196 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
197 let language_ids = adapter.language_ids();
198
199 Arc::new(CachedLspAdapter {
200 name,
201 disk_based_diagnostic_sources,
202 disk_based_diagnostics_progress_token,
203 language_ids,
204 adapter,
205 cached_binary: Default::default(),
206 reinstall_attempt_count: AtomicU64::new(0),
207 attach_kind: Default::default(),
208 manifest_name: Default::default(),
209 })
210 }
211
212 pub fn name(&self) -> LanguageServerName {
213 self.adapter.name().clone()
214 }
215
216 pub async fn get_language_server_command(
217 self: Arc<Self>,
218 delegate: Arc<dyn LspAdapterDelegate>,
219 toolchains: Arc<dyn LanguageToolchainStore>,
220 binary_options: LanguageServerBinaryOptions,
221 cx: &mut AsyncApp,
222 ) -> Result<LanguageServerBinary> {
223 let cached_binary = self.cached_binary.lock().await;
224 self.adapter
225 .clone()
226 .get_language_server_command(delegate, toolchains, binary_options, cached_binary, cx)
227 .await
228 }
229
230 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
231 self.adapter.code_action_kinds()
232 }
233
234 pub fn process_diagnostics(
235 &self,
236 params: &mut lsp::PublishDiagnosticsParams,
237 server_id: LanguageServerId,
238 existing_diagnostics: Option<&'_ Buffer>,
239 ) {
240 self.adapter
241 .process_diagnostics(params, server_id, existing_diagnostics)
242 }
243
244 pub fn retain_old_diagnostic(&self, previous_diagnostic: &Diagnostic, cx: &App) -> bool {
245 self.adapter.retain_old_diagnostic(previous_diagnostic, cx)
246 }
247
248 pub fn underline_diagnostic(&self, diagnostic: &lsp::Diagnostic) -> bool {
249 self.adapter.underline_diagnostic(diagnostic)
250 }
251
252 pub fn diagnostic_message_to_markdown(&self, message: &str) -> Option<String> {
253 self.adapter.diagnostic_message_to_markdown(message)
254 }
255
256 pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
257 self.adapter.process_completions(completion_items).await
258 }
259
260 pub async fn labels_for_completions(
261 &self,
262 completion_items: &[lsp::CompletionItem],
263 language: &Arc<Language>,
264 ) -> Result<Vec<Option<CodeLabel>>> {
265 self.adapter
266 .clone()
267 .labels_for_completions(completion_items, language)
268 .await
269 }
270
271 pub async fn labels_for_symbols(
272 &self,
273 symbols: &[(String, lsp::SymbolKind)],
274 language: &Arc<Language>,
275 ) -> Result<Vec<Option<CodeLabel>>> {
276 self.adapter
277 .clone()
278 .labels_for_symbols(symbols, language)
279 .await
280 }
281
282 pub fn language_id(&self, language_name: &LanguageName) -> String {
283 self.language_ids
284 .get(language_name.as_ref())
285 .cloned()
286 .unwrap_or_else(|| language_name.lsp_id())
287 }
288 pub fn manifest_name(&self) -> Option<ManifestName> {
289 self.manifest_name
290 .get_or_init(|| self.adapter.manifest_name())
291 .clone()
292 }
293 pub fn attach_kind(&self) -> Attach {
294 *self.attach_kind.get_or_init(|| self.adapter.attach_kind())
295 }
296}
297
298#[derive(Clone, Copy, Debug, PartialEq)]
299pub enum Attach {
300 /// Create a single language server instance per subproject root.
301 InstancePerRoot,
302 /// Use one shared language server instance for all subprojects within a project.
303 Shared,
304}
305
306impl Attach {
307 pub fn root_path(
308 &self,
309 root_subproject_path: (WorktreeId, Arc<Path>),
310 ) -> (WorktreeId, Arc<Path>) {
311 match self {
312 Attach::InstancePerRoot => root_subproject_path,
313 Attach::Shared => (root_subproject_path.0, Arc::from(Path::new(""))),
314 }
315 }
316}
317
318/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
319// e.g. to display a notification or fetch data from the web.
320#[async_trait]
321pub trait LspAdapterDelegate: Send + Sync {
322 fn show_notification(&self, message: &str, cx: &mut App);
323 fn http_client(&self) -> Arc<dyn HttpClient>;
324 fn worktree_id(&self) -> WorktreeId;
325 fn worktree_root_path(&self) -> &Path;
326 fn update_status(&self, language: LanguageServerName, status: BinaryStatus);
327 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>>;
328 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
329
330 async fn npm_package_installed_version(
331 &self,
332 package_name: &str,
333 ) -> Result<Option<(PathBuf, String)>>;
334 async fn which(&self, command: &OsStr) -> Option<PathBuf>;
335 async fn shell_env(&self) -> HashMap<String, String>;
336 async fn read_text_file(&self, path: PathBuf) -> Result<String>;
337 async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
338}
339
340#[async_trait(?Send)]
341pub trait LspAdapter: 'static + Send + Sync {
342 fn name(&self) -> LanguageServerName;
343
344 fn get_language_server_command<'a>(
345 self: Arc<Self>,
346 delegate: Arc<dyn LspAdapterDelegate>,
347 toolchains: Arc<dyn LanguageToolchainStore>,
348 binary_options: LanguageServerBinaryOptions,
349 mut cached_binary: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
350 cx: &'a mut AsyncApp,
351 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
352 async move {
353 // First we check whether the adapter can give us a user-installed binary.
354 // If so, we do *not* want to cache that, because each worktree might give us a different
355 // binary:
356 //
357 // worktree 1: user-installed at `.bin/gopls`
358 // worktree 2: user-installed at `~/bin/gopls`
359 // worktree 3: no gopls found in PATH -> fallback to Zed installation
360 //
361 // We only want to cache when we fall back to the global one,
362 // because we don't want to download and overwrite our global one
363 // for each worktree we might have open.
364 if binary_options.allow_path_lookup {
365 if let Some(binary) = self.check_if_user_installed(delegate.as_ref(), toolchains, cx).await {
366 log::info!(
367 "found user-installed language server for {}. path: {:?}, arguments: {:?}",
368 self.name().0,
369 binary.path,
370 binary.arguments
371 );
372 return Ok(binary);
373 }
374 }
375
376 anyhow::ensure!(binary_options.allow_binary_download, "downloading language servers disabled");
377
378 if let Some(cached_binary) = cached_binary.as_ref() {
379 return Ok(cached_binary.clone());
380 }
381
382 let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await else {
383 anyhow::bail!("no language server download dir defined")
384 };
385
386 let mut binary = try_fetch_server_binary(self.as_ref(), &delegate, container_dir.to_path_buf(), cx).await;
387
388 if let Err(error) = binary.as_ref() {
389 if let Some(prev_downloaded_binary) = self
390 .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
391 .await
392 {
393 log::info!(
394 "failed to fetch newest version of language server {:?}. error: {:?}, falling back to using {:?}",
395 self.name(),
396 error,
397 prev_downloaded_binary.path
398 );
399 binary = Ok(prev_downloaded_binary);
400 } else {
401 delegate.update_status(
402 self.name(),
403 BinaryStatus::Failed {
404 error: format!("{error:?}"),
405 },
406 );
407 }
408 }
409
410 if let Ok(binary) = &binary {
411 *cached_binary = Some(binary.clone());
412 }
413
414 binary
415 }
416 .boxed_local()
417 }
418
419 async fn check_if_user_installed(
420 &self,
421 _: &dyn LspAdapterDelegate,
422 _: Arc<dyn LanguageToolchainStore>,
423 _: &AsyncApp,
424 ) -> Option<LanguageServerBinary> {
425 None
426 }
427
428 async fn fetch_latest_server_version(
429 &self,
430 delegate: &dyn LspAdapterDelegate,
431 ) -> Result<Box<dyn 'static + Send + Any>>;
432
433 fn will_fetch_server(
434 &self,
435 _: &Arc<dyn LspAdapterDelegate>,
436 _: &mut AsyncApp,
437 ) -> Option<Task<Result<()>>> {
438 None
439 }
440
441 async fn check_if_version_installed(
442 &self,
443 _version: &(dyn 'static + Send + Any),
444 _container_dir: &PathBuf,
445 _delegate: &dyn LspAdapterDelegate,
446 ) -> Option<LanguageServerBinary> {
447 None
448 }
449
450 async fn fetch_server_binary(
451 &self,
452 latest_version: Box<dyn 'static + Send + Any>,
453 container_dir: PathBuf,
454 delegate: &dyn LspAdapterDelegate,
455 ) -> Result<LanguageServerBinary>;
456
457 async fn cached_server_binary(
458 &self,
459 container_dir: PathBuf,
460 delegate: &dyn LspAdapterDelegate,
461 ) -> Option<LanguageServerBinary>;
462
463 fn process_diagnostics(
464 &self,
465 _: &mut lsp::PublishDiagnosticsParams,
466 _: LanguageServerId,
467 _: Option<&'_ Buffer>,
468 ) {
469 }
470
471 /// When processing new `lsp::PublishDiagnosticsParams` diagnostics, whether to retain previous one(s) or not.
472 fn retain_old_diagnostic(&self, _previous_diagnostic: &Diagnostic, _cx: &App) -> bool {
473 false
474 }
475
476 /// Whether to underline a given diagnostic or not, when rendering in the editor.
477 ///
478 /// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#diagnosticTag
479 /// states that
480 /// > Clients are allowed to render diagnostics with this tag faded out instead of having an error squiggle.
481 /// for the unnecessary diagnostics, so do not underline them.
482 fn underline_diagnostic(&self, _diagnostic: &lsp::Diagnostic) -> bool {
483 true
484 }
485
486 /// Post-processes completions provided by the language server.
487 async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
488
489 fn diagnostic_message_to_markdown(&self, _message: &str) -> Option<String> {
490 None
491 }
492
493 async fn labels_for_completions(
494 self: Arc<Self>,
495 completions: &[lsp::CompletionItem],
496 language: &Arc<Language>,
497 ) -> Result<Vec<Option<CodeLabel>>> {
498 let mut labels = Vec::new();
499 for (ix, completion) in completions.iter().enumerate() {
500 let label = self.label_for_completion(completion, language).await;
501 if let Some(label) = label {
502 labels.resize(ix + 1, None);
503 *labels.last_mut().unwrap() = Some(label);
504 }
505 }
506 Ok(labels)
507 }
508
509 async fn label_for_completion(
510 &self,
511 _: &lsp::CompletionItem,
512 _: &Arc<Language>,
513 ) -> Option<CodeLabel> {
514 None
515 }
516
517 async fn labels_for_symbols(
518 self: Arc<Self>,
519 symbols: &[(String, lsp::SymbolKind)],
520 language: &Arc<Language>,
521 ) -> Result<Vec<Option<CodeLabel>>> {
522 let mut labels = Vec::new();
523 for (ix, (name, kind)) in symbols.iter().enumerate() {
524 let label = self.label_for_symbol(name, *kind, language).await;
525 if let Some(label) = label {
526 labels.resize(ix + 1, None);
527 *labels.last_mut().unwrap() = Some(label);
528 }
529 }
530 Ok(labels)
531 }
532
533 async fn label_for_symbol(
534 &self,
535 _: &str,
536 _: lsp::SymbolKind,
537 _: &Arc<Language>,
538 ) -> Option<CodeLabel> {
539 None
540 }
541
542 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
543 async fn initialization_options(
544 self: Arc<Self>,
545 _: &dyn Fs,
546 _: &Arc<dyn LspAdapterDelegate>,
547 ) -> Result<Option<Value>> {
548 Ok(None)
549 }
550
551 async fn workspace_configuration(
552 self: Arc<Self>,
553 _: &dyn Fs,
554 _: &Arc<dyn LspAdapterDelegate>,
555 _: Arc<dyn LanguageToolchainStore>,
556 _cx: &mut AsyncApp,
557 ) -> Result<Value> {
558 Ok(serde_json::json!({}))
559 }
560
561 async fn additional_initialization_options(
562 self: Arc<Self>,
563 _target_language_server_id: LanguageServerName,
564 _: &dyn Fs,
565 _: &Arc<dyn LspAdapterDelegate>,
566 ) -> Result<Option<Value>> {
567 Ok(None)
568 }
569
570 async fn additional_workspace_configuration(
571 self: Arc<Self>,
572 _target_language_server_id: LanguageServerName,
573 _: &dyn Fs,
574 _: &Arc<dyn LspAdapterDelegate>,
575 _: Arc<dyn LanguageToolchainStore>,
576 _cx: &mut AsyncApp,
577 ) -> Result<Option<Value>> {
578 Ok(None)
579 }
580
581 /// Returns a list of code actions supported by a given LspAdapter
582 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
583 None
584 }
585
586 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
587 Default::default()
588 }
589
590 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
591 None
592 }
593
594 fn language_ids(&self) -> HashMap<String, String> {
595 Default::default()
596 }
597
598 /// Support custom initialize params.
599 fn prepare_initialize_params(
600 &self,
601 original: InitializeParams,
602 _: &App,
603 ) -> Result<InitializeParams> {
604 Ok(original)
605 }
606
607 fn attach_kind(&self) -> Attach {
608 Attach::Shared
609 }
610
611 fn manifest_name(&self) -> Option<ManifestName> {
612 None
613 }
614
615 /// Method only implemented by the default JSON language server adapter.
616 /// Used to provide dynamic reloading of the JSON schemas used to
617 /// provide autocompletion and diagnostics in Zed setting and keybind
618 /// files
619 fn is_primary_zed_json_schema_adapter(&self) -> bool {
620 false
621 }
622
623 /// Method only implemented by the default JSON language server adapter.
624 /// Used to clear the cache of JSON schemas that are used to provide
625 /// autocompletion and diagnostics in Zed settings and keybinds files.
626 /// Should not be called unless the callee is sure that
627 /// `Self::is_primary_zed_json_schema_adapter` returns `true`
628 async fn clear_zed_json_schema_cache(&self) {
629 unreachable!(
630 "Not implemented for this adapter. This method should only be called on the default JSON language server adapter"
631 );
632 }
633}
634
635async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
636 adapter: &L,
637 delegate: &Arc<dyn LspAdapterDelegate>,
638 container_dir: PathBuf,
639 cx: &mut AsyncApp,
640) -> Result<LanguageServerBinary> {
641 if let Some(task) = adapter.will_fetch_server(delegate, cx) {
642 task.await?;
643 }
644
645 let name = adapter.name();
646 log::info!("fetching latest version of language server {:?}", name.0);
647 delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
648
649 let latest_version = adapter
650 .fetch_latest_server_version(delegate.as_ref())
651 .await?;
652
653 if let Some(binary) = adapter
654 .check_if_version_installed(latest_version.as_ref(), &container_dir, delegate.as_ref())
655 .await
656 {
657 log::info!("language server {:?} is already installed", name.0);
658 delegate.update_status(name.clone(), BinaryStatus::None);
659 Ok(binary)
660 } else {
661 log::info!("downloading language server {:?}", name.0);
662 delegate.update_status(adapter.name(), BinaryStatus::Downloading);
663 let binary = adapter
664 .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
665 .await;
666
667 delegate.update_status(name.clone(), BinaryStatus::None);
668 binary
669 }
670}
671
672#[derive(Clone, Debug, Default, PartialEq, Eq)]
673pub struct CodeLabel {
674 /// The text to display.
675 pub text: String,
676 /// Syntax highlighting runs.
677 pub runs: Vec<(Range<usize>, HighlightId)>,
678 /// The portion of the text that should be used in fuzzy filtering.
679 pub filter_range: Range<usize>,
680}
681
682#[derive(Clone, Deserialize, JsonSchema)]
683pub struct LanguageConfig {
684 /// Human-readable name of the language.
685 pub name: LanguageName,
686 /// The name of this language for a Markdown code fence block
687 pub code_fence_block_name: Option<Arc<str>>,
688 // The name of the grammar in a WASM bundle (experimental).
689 pub grammar: Option<Arc<str>>,
690 /// The criteria for matching this language to a given file.
691 #[serde(flatten)]
692 pub matcher: LanguageMatcher,
693 /// List of bracket types in a language.
694 #[serde(default)]
695 #[schemars(schema_with = "bracket_pair_config_json_schema")]
696 pub brackets: BracketPairConfig,
697 /// If set to true, indicates the language uses significant whitespace/indentation
698 /// for syntax structure (like Python) rather than brackets/braces for code blocks.
699 #[serde(default)]
700 pub significant_indentation: bool,
701 /// If set to true, auto indentation uses last non empty line to determine
702 /// the indentation level for a new line.
703 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
704 pub auto_indent_using_last_non_empty_line: bool,
705 // Whether indentation of pasted content should be adjusted based on the context.
706 #[serde(default)]
707 pub auto_indent_on_paste: Option<bool>,
708 /// A regex that is used to determine whether the indentation level should be
709 /// increased in the following line.
710 #[serde(default, deserialize_with = "deserialize_regex")]
711 #[schemars(schema_with = "regex_json_schema")]
712 pub increase_indent_pattern: Option<Regex>,
713 /// A regex that is used to determine whether the indentation level should be
714 /// decreased in the following line.
715 #[serde(default, deserialize_with = "deserialize_regex")]
716 #[schemars(schema_with = "regex_json_schema")]
717 pub decrease_indent_pattern: Option<Regex>,
718 /// A list of characters that trigger the automatic insertion of a closing
719 /// bracket when they immediately precede the point where an opening
720 /// bracket is inserted.
721 #[serde(default)]
722 pub autoclose_before: String,
723 /// A placeholder used internally by Semantic Index.
724 #[serde(default)]
725 pub collapsed_placeholder: String,
726 /// A line comment string that is inserted in e.g. `toggle comments` action.
727 /// A language can have multiple flavours of line comments. All of the provided line comments are
728 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
729 #[serde(default)]
730 pub line_comments: Vec<Arc<str>>,
731 /// Starting and closing characters of a block comment.
732 #[serde(default)]
733 pub block_comment: Option<(Arc<str>, Arc<str>)>,
734 /// A list of language servers that are allowed to run on subranges of a given language.
735 #[serde(default)]
736 pub scope_opt_in_language_servers: Vec<LanguageServerName>,
737 #[serde(default)]
738 pub overrides: HashMap<String, LanguageConfigOverride>,
739 /// A list of characters that Zed should treat as word characters for the
740 /// purpose of features that operate on word boundaries, like 'move to next word end'
741 /// or a whole-word search in buffer search.
742 #[serde(default)]
743 pub word_characters: HashSet<char>,
744 /// Whether to indent lines using tab characters, as opposed to multiple
745 /// spaces.
746 #[serde(default)]
747 pub hard_tabs: Option<bool>,
748 /// How many columns a tab should occupy.
749 #[serde(default)]
750 pub tab_size: Option<NonZeroU32>,
751 /// How to soft-wrap long lines of text.
752 #[serde(default)]
753 pub soft_wrap: Option<SoftWrap>,
754 /// The name of a Prettier parser that will be used for this language when no file path is available.
755 /// If there's a parser name in the language settings, that will be used instead.
756 #[serde(default)]
757 pub prettier_parser_name: Option<String>,
758 /// If true, this language is only for syntax highlighting via an injection into other
759 /// languages, but should not appear to the user as a distinct language.
760 #[serde(default)]
761 pub hidden: bool,
762 /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
763 #[serde(default)]
764 pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
765 /// A list of characters that Zed should treat as word characters for completion queries.
766 #[serde(default)]
767 pub completion_query_characters: HashSet<char>,
768 /// A list of preferred debuggers for this language.
769 #[serde(default)]
770 pub debuggers: IndexSet<SharedString>,
771 /// Whether to treat documentation comment of this language differently by
772 /// auto adding prefix on new line, adjusting the indenting , etc.
773 #[serde(default)]
774 pub documentation: Option<DocumentationConfig>,
775}
776
777#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
778pub struct LanguageMatcher {
779 /// 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`.
780 #[serde(default)]
781 pub path_suffixes: Vec<String>,
782 /// A regex pattern that determines whether the language should be assigned to a file or not.
783 #[serde(
784 default,
785 serialize_with = "serialize_regex",
786 deserialize_with = "deserialize_regex"
787 )]
788 #[schemars(schema_with = "regex_json_schema")]
789 pub first_line_pattern: Option<Regex>,
790}
791
792/// The configuration for JSX tag auto-closing.
793#[derive(Clone, Deserialize, JsonSchema)]
794pub struct JsxTagAutoCloseConfig {
795 /// The name of the node for a opening tag
796 pub open_tag_node_name: String,
797 /// The name of the node for an closing tag
798 pub close_tag_node_name: String,
799 /// The name of the node for a complete element with children for open and close tags
800 pub jsx_element_node_name: String,
801 /// The name of the node found within both opening and closing
802 /// tags that describes the tag name
803 pub tag_name_node_name: String,
804 /// Alternate Node names for tag names.
805 /// Specifically needed as TSX represents the name in `<Foo.Bar>`
806 /// as `member_expression` rather than `identifier` as usual
807 #[serde(default)]
808 pub tag_name_node_name_alternates: Vec<String>,
809 /// Some grammars are smart enough to detect a closing tag
810 /// that is not valid i.e. doesn't match it's corresponding
811 /// opening tag or does not have a corresponding opening tag
812 /// This should be set to the name of the node for invalid
813 /// closing tags if the grammar contains such a node, otherwise
814 /// detecting already closed tags will not work properly
815 #[serde(default)]
816 pub erroneous_close_tag_node_name: Option<String>,
817 /// See above for erroneous_close_tag_node_name for details
818 /// This should be set if the node used for the tag name
819 /// within erroneous closing tags is different from the
820 /// normal tag name node name
821 #[serde(default)]
822 pub erroneous_close_tag_name_node_name: Option<String>,
823}
824
825/// The configuration for documentation block for this language.
826#[derive(Clone, Deserialize, JsonSchema)]
827pub struct DocumentationConfig {
828 /// A start tag of documentation block.
829 pub start: Arc<str>,
830 /// A end tag of documentation block.
831 pub end: Arc<str>,
832 /// A character to add as a prefix when a new line is added to a documentation block.
833 pub prefix: Arc<str>,
834 /// A indent to add for prefix and end line upon new line.
835 pub tab_size: NonZeroU32,
836}
837
838/// Represents a language for the given range. Some languages (e.g. HTML)
839/// interleave several languages together, thus a single buffer might actually contain
840/// several nested scopes.
841#[derive(Clone, Debug)]
842pub struct LanguageScope {
843 language: Arc<Language>,
844 override_id: Option<u32>,
845}
846
847#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
848pub struct LanguageConfigOverride {
849 #[serde(default)]
850 pub line_comments: Override<Vec<Arc<str>>>,
851 #[serde(default)]
852 pub block_comment: Override<(Arc<str>, Arc<str>)>,
853 #[serde(skip)]
854 pub disabled_bracket_ixs: Vec<u16>,
855 #[serde(default)]
856 pub word_characters: Override<HashSet<char>>,
857 #[serde(default)]
858 pub completion_query_characters: Override<HashSet<char>>,
859 #[serde(default)]
860 pub opt_into_language_servers: Vec<LanguageServerName>,
861 #[serde(default)]
862 pub prefer_label_for_snippet: Option<bool>,
863}
864
865#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
866#[serde(untagged)]
867pub enum Override<T> {
868 Remove { remove: bool },
869 Set(T),
870}
871
872impl<T> Default for Override<T> {
873 fn default() -> Self {
874 Override::Remove { remove: false }
875 }
876}
877
878impl<T> Override<T> {
879 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
880 match this {
881 Some(Self::Set(value)) => Some(value),
882 Some(Self::Remove { remove: true }) => None,
883 Some(Self::Remove { remove: false }) | None => original,
884 }
885 }
886}
887
888impl Default for LanguageConfig {
889 fn default() -> Self {
890 Self {
891 name: LanguageName::new(""),
892 code_fence_block_name: None,
893 grammar: None,
894 matcher: LanguageMatcher::default(),
895 brackets: Default::default(),
896 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
897 auto_indent_on_paste: None,
898 increase_indent_pattern: Default::default(),
899 decrease_indent_pattern: Default::default(),
900 autoclose_before: Default::default(),
901 line_comments: Default::default(),
902 block_comment: Default::default(),
903 scope_opt_in_language_servers: Default::default(),
904 overrides: Default::default(),
905 word_characters: Default::default(),
906 collapsed_placeholder: Default::default(),
907 hard_tabs: None,
908 tab_size: None,
909 soft_wrap: None,
910 prettier_parser_name: None,
911 hidden: false,
912 jsx_tag_auto_close: None,
913 completion_query_characters: Default::default(),
914 debuggers: Default::default(),
915 significant_indentation: Default::default(),
916 documentation: None,
917 }
918 }
919}
920
921fn auto_indent_using_last_non_empty_line_default() -> bool {
922 true
923}
924
925fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
926 let source = Option::<String>::deserialize(d)?;
927 if let Some(source) = source {
928 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
929 } else {
930 Ok(None)
931 }
932}
933
934fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
935 Schema::Object(SchemaObject {
936 instance_type: Some(InstanceType::String.into()),
937 ..Default::default()
938 })
939}
940
941fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
942where
943 S: Serializer,
944{
945 match regex {
946 Some(regex) => serializer.serialize_str(regex.as_str()),
947 None => serializer.serialize_none(),
948 }
949}
950
951#[doc(hidden)]
952#[cfg(any(test, feature = "test-support"))]
953pub struct FakeLspAdapter {
954 pub name: &'static str,
955 pub initialization_options: Option<Value>,
956 pub prettier_plugins: Vec<&'static str>,
957 pub disk_based_diagnostics_progress_token: Option<String>,
958 pub disk_based_diagnostics_sources: Vec<String>,
959 pub language_server_binary: LanguageServerBinary,
960
961 pub capabilities: lsp::ServerCapabilities,
962 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
963 pub label_for_completion: Option<
964 Box<
965 dyn 'static
966 + Send
967 + Sync
968 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
969 >,
970 >,
971}
972
973/// Configuration of handling bracket pairs for a given language.
974///
975/// This struct includes settings for defining which pairs of characters are considered brackets and
976/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
977#[derive(Clone, Debug, Default, JsonSchema)]
978pub struct BracketPairConfig {
979 /// A list of character pairs that should be treated as brackets in the context of a given language.
980 pub pairs: Vec<BracketPair>,
981 /// A list of tree-sitter scopes for which a given bracket should not be active.
982 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
983 #[serde(skip)]
984 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
985}
986
987impl BracketPairConfig {
988 pub fn is_closing_brace(&self, c: char) -> bool {
989 self.pairs.iter().any(|pair| pair.end.starts_with(c))
990 }
991}
992
993fn bracket_pair_config_json_schema(r#gen: &mut SchemaGenerator) -> Schema {
994 Option::<Vec<BracketPairContent>>::json_schema(r#gen)
995}
996
997#[derive(Deserialize, JsonSchema)]
998pub struct BracketPairContent {
999 #[serde(flatten)]
1000 pub bracket_pair: BracketPair,
1001 #[serde(default)]
1002 pub not_in: Vec<String>,
1003}
1004
1005impl<'de> Deserialize<'de> for BracketPairConfig {
1006 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1007 where
1008 D: Deserializer<'de>,
1009 {
1010 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
1011 let mut brackets = Vec::with_capacity(result.len());
1012 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
1013 for entry in result {
1014 brackets.push(entry.bracket_pair);
1015 disabled_scopes_by_bracket_ix.push(entry.not_in);
1016 }
1017
1018 Ok(BracketPairConfig {
1019 pairs: brackets,
1020 disabled_scopes_by_bracket_ix,
1021 })
1022 }
1023}
1024
1025/// Describes a single bracket pair and how an editor should react to e.g. inserting
1026/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
1027#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
1028pub struct BracketPair {
1029 /// Starting substring for a bracket.
1030 pub start: String,
1031 /// Ending substring for a bracket.
1032 pub end: String,
1033 /// True if `end` should be automatically inserted right after `start` characters.
1034 pub close: bool,
1035 /// True if selected text should be surrounded by `start` and `end` characters.
1036 #[serde(default = "default_true")]
1037 pub surround: bool,
1038 /// True if an extra newline should be inserted while the cursor is in the middle
1039 /// of that bracket pair.
1040 pub newline: bool,
1041}
1042
1043#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1044pub struct LanguageId(usize);
1045
1046impl LanguageId {
1047 pub(crate) fn new() -> Self {
1048 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
1049 }
1050}
1051
1052pub struct Language {
1053 pub(crate) id: LanguageId,
1054 pub(crate) config: LanguageConfig,
1055 pub(crate) grammar: Option<Arc<Grammar>>,
1056 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1057 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1058}
1059
1060#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1061pub struct GrammarId(pub usize);
1062
1063impl GrammarId {
1064 pub(crate) fn new() -> Self {
1065 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1066 }
1067}
1068
1069pub struct Grammar {
1070 id: GrammarId,
1071 pub ts_language: tree_sitter::Language,
1072 pub(crate) error_query: Option<Query>,
1073 pub(crate) highlights_query: Option<Query>,
1074 pub(crate) brackets_config: Option<BracketsConfig>,
1075 pub(crate) redactions_config: Option<RedactionConfig>,
1076 pub(crate) runnable_config: Option<RunnableConfig>,
1077 pub(crate) indents_config: Option<IndentConfig>,
1078 pub outline_config: Option<OutlineConfig>,
1079 pub text_object_config: Option<TextObjectConfig>,
1080 pub embedding_config: Option<EmbeddingConfig>,
1081 pub(crate) injection_config: Option<InjectionConfig>,
1082 pub(crate) override_config: Option<OverrideConfig>,
1083 pub(crate) highlight_map: Mutex<HighlightMap>,
1084}
1085
1086struct IndentConfig {
1087 query: Query,
1088 indent_capture_ix: u32,
1089 start_capture_ix: Option<u32>,
1090 end_capture_ix: Option<u32>,
1091 outdent_capture_ix: Option<u32>,
1092}
1093
1094pub struct OutlineConfig {
1095 pub query: Query,
1096 pub item_capture_ix: u32,
1097 pub name_capture_ix: u32,
1098 pub context_capture_ix: Option<u32>,
1099 pub extra_context_capture_ix: Option<u32>,
1100 pub open_capture_ix: Option<u32>,
1101 pub close_capture_ix: Option<u32>,
1102 pub annotation_capture_ix: Option<u32>,
1103}
1104
1105#[derive(Debug, Clone, Copy, PartialEq)]
1106pub enum TextObject {
1107 InsideFunction,
1108 AroundFunction,
1109 InsideClass,
1110 AroundClass,
1111 InsideComment,
1112 AroundComment,
1113}
1114
1115impl TextObject {
1116 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1117 match name {
1118 "function.inside" => Some(TextObject::InsideFunction),
1119 "function.around" => Some(TextObject::AroundFunction),
1120 "class.inside" => Some(TextObject::InsideClass),
1121 "class.around" => Some(TextObject::AroundClass),
1122 "comment.inside" => Some(TextObject::InsideComment),
1123 "comment.around" => Some(TextObject::AroundComment),
1124 _ => None,
1125 }
1126 }
1127
1128 pub fn around(&self) -> Option<Self> {
1129 match self {
1130 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1131 TextObject::InsideClass => Some(TextObject::AroundClass),
1132 TextObject::InsideComment => Some(TextObject::AroundComment),
1133 _ => None,
1134 }
1135 }
1136}
1137
1138pub struct TextObjectConfig {
1139 pub query: Query,
1140 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1141}
1142
1143#[derive(Debug)]
1144pub struct EmbeddingConfig {
1145 pub query: Query,
1146 pub item_capture_ix: u32,
1147 pub name_capture_ix: Option<u32>,
1148 pub context_capture_ix: Option<u32>,
1149 pub collapse_capture_ix: Option<u32>,
1150 pub keep_capture_ix: Option<u32>,
1151}
1152
1153struct InjectionConfig {
1154 query: Query,
1155 content_capture_ix: u32,
1156 language_capture_ix: Option<u32>,
1157 patterns: Vec<InjectionPatternConfig>,
1158}
1159
1160struct RedactionConfig {
1161 pub query: Query,
1162 pub redaction_capture_ix: u32,
1163}
1164
1165#[derive(Clone, Debug, PartialEq)]
1166enum RunnableCapture {
1167 Named(SharedString),
1168 Run,
1169}
1170
1171struct RunnableConfig {
1172 pub query: Query,
1173 /// A mapping from capture indice to capture kind
1174 pub extra_captures: Vec<RunnableCapture>,
1175}
1176
1177struct OverrideConfig {
1178 query: Query,
1179 values: HashMap<u32, OverrideEntry>,
1180}
1181
1182#[derive(Debug)]
1183struct OverrideEntry {
1184 name: String,
1185 range_is_inclusive: bool,
1186 value: LanguageConfigOverride,
1187}
1188
1189#[derive(Default, Clone)]
1190struct InjectionPatternConfig {
1191 language: Option<Box<str>>,
1192 combined: bool,
1193}
1194
1195struct BracketsConfig {
1196 query: Query,
1197 open_capture_ix: u32,
1198 close_capture_ix: u32,
1199 patterns: Vec<BracketsPatternConfig>,
1200}
1201
1202#[derive(Clone, Debug, Default)]
1203struct BracketsPatternConfig {
1204 newline_only: bool,
1205}
1206
1207impl Language {
1208 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1209 Self::new_with_id(LanguageId::new(), config, ts_language)
1210 }
1211
1212 pub fn id(&self) -> LanguageId {
1213 self.id
1214 }
1215
1216 fn new_with_id(
1217 id: LanguageId,
1218 config: LanguageConfig,
1219 ts_language: Option<tree_sitter::Language>,
1220 ) -> Self {
1221 Self {
1222 id,
1223 config,
1224 grammar: ts_language.map(|ts_language| {
1225 Arc::new(Grammar {
1226 id: GrammarId::new(),
1227 highlights_query: None,
1228 brackets_config: None,
1229 outline_config: None,
1230 text_object_config: None,
1231 embedding_config: None,
1232 indents_config: None,
1233 injection_config: None,
1234 override_config: None,
1235 redactions_config: None,
1236 runnable_config: None,
1237 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1238 ts_language,
1239 highlight_map: Default::default(),
1240 })
1241 }),
1242 context_provider: None,
1243 toolchain: None,
1244 }
1245 }
1246
1247 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1248 self.context_provider = provider;
1249 self
1250 }
1251
1252 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1253 self.toolchain = provider;
1254 self
1255 }
1256
1257 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1258 if let Some(query) = queries.highlights {
1259 self = self
1260 .with_highlights_query(query.as_ref())
1261 .context("Error loading highlights query")?;
1262 }
1263 if let Some(query) = queries.brackets {
1264 self = self
1265 .with_brackets_query(query.as_ref())
1266 .context("Error loading brackets query")?;
1267 }
1268 if let Some(query) = queries.indents {
1269 self = self
1270 .with_indents_query(query.as_ref())
1271 .context("Error loading indents query")?;
1272 }
1273 if let Some(query) = queries.outline {
1274 self = self
1275 .with_outline_query(query.as_ref())
1276 .context("Error loading outline query")?;
1277 }
1278 if let Some(query) = queries.embedding {
1279 self = self
1280 .with_embedding_query(query.as_ref())
1281 .context("Error loading embedding query")?;
1282 }
1283 if let Some(query) = queries.injections {
1284 self = self
1285 .with_injection_query(query.as_ref())
1286 .context("Error loading injection query")?;
1287 }
1288 if let Some(query) = queries.overrides {
1289 self = self
1290 .with_override_query(query.as_ref())
1291 .context("Error loading override query")?;
1292 }
1293 if let Some(query) = queries.redactions {
1294 self = self
1295 .with_redaction_query(query.as_ref())
1296 .context("Error loading redaction query")?;
1297 }
1298 if let Some(query) = queries.runnables {
1299 self = self
1300 .with_runnable_query(query.as_ref())
1301 .context("Error loading runnables query")?;
1302 }
1303 if let Some(query) = queries.text_objects {
1304 self = self
1305 .with_text_object_query(query.as_ref())
1306 .context("Error loading textobject query")?;
1307 }
1308 Ok(self)
1309 }
1310
1311 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1312 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1313 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1314 Ok(self)
1315 }
1316
1317 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1318 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1319
1320 let query = Query::new(&grammar.ts_language, source)?;
1321 let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1322
1323 for name in query.capture_names().iter() {
1324 let kind = if *name == "run" {
1325 RunnableCapture::Run
1326 } else {
1327 RunnableCapture::Named(name.to_string().into())
1328 };
1329 extra_captures.push(kind);
1330 }
1331
1332 grammar.runnable_config = Some(RunnableConfig {
1333 extra_captures,
1334 query,
1335 });
1336
1337 Ok(self)
1338 }
1339
1340 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1341 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1342 let query = Query::new(&grammar.ts_language, source)?;
1343 let mut item_capture_ix = None;
1344 let mut name_capture_ix = None;
1345 let mut context_capture_ix = None;
1346 let mut extra_context_capture_ix = None;
1347 let mut open_capture_ix = None;
1348 let mut close_capture_ix = None;
1349 let mut annotation_capture_ix = None;
1350 get_capture_indices(
1351 &query,
1352 &mut [
1353 ("item", &mut item_capture_ix),
1354 ("name", &mut name_capture_ix),
1355 ("context", &mut context_capture_ix),
1356 ("context.extra", &mut extra_context_capture_ix),
1357 ("open", &mut open_capture_ix),
1358 ("close", &mut close_capture_ix),
1359 ("annotation", &mut annotation_capture_ix),
1360 ],
1361 );
1362 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1363 grammar.outline_config = Some(OutlineConfig {
1364 query,
1365 item_capture_ix,
1366 name_capture_ix,
1367 context_capture_ix,
1368 extra_context_capture_ix,
1369 open_capture_ix,
1370 close_capture_ix,
1371 annotation_capture_ix,
1372 });
1373 }
1374 Ok(self)
1375 }
1376
1377 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1378 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1379 let query = Query::new(&grammar.ts_language, source)?;
1380
1381 let mut text_objects_by_capture_ix = Vec::new();
1382 for (ix, name) in query.capture_names().iter().enumerate() {
1383 if let Some(text_object) = TextObject::from_capture_name(name) {
1384 text_objects_by_capture_ix.push((ix as u32, text_object));
1385 }
1386 }
1387
1388 grammar.text_object_config = Some(TextObjectConfig {
1389 query,
1390 text_objects_by_capture_ix,
1391 });
1392 Ok(self)
1393 }
1394
1395 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1396 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1397 let query = Query::new(&grammar.ts_language, source)?;
1398 let mut item_capture_ix = None;
1399 let mut name_capture_ix = None;
1400 let mut context_capture_ix = None;
1401 let mut collapse_capture_ix = None;
1402 let mut keep_capture_ix = None;
1403 get_capture_indices(
1404 &query,
1405 &mut [
1406 ("item", &mut item_capture_ix),
1407 ("name", &mut name_capture_ix),
1408 ("context", &mut context_capture_ix),
1409 ("keep", &mut keep_capture_ix),
1410 ("collapse", &mut collapse_capture_ix),
1411 ],
1412 );
1413 if let Some(item_capture_ix) = item_capture_ix {
1414 grammar.embedding_config = Some(EmbeddingConfig {
1415 query,
1416 item_capture_ix,
1417 name_capture_ix,
1418 context_capture_ix,
1419 collapse_capture_ix,
1420 keep_capture_ix,
1421 });
1422 }
1423 Ok(self)
1424 }
1425
1426 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1427 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1428 let query = Query::new(&grammar.ts_language, source)?;
1429 let mut open_capture_ix = None;
1430 let mut close_capture_ix = None;
1431 get_capture_indices(
1432 &query,
1433 &mut [
1434 ("open", &mut open_capture_ix),
1435 ("close", &mut close_capture_ix),
1436 ],
1437 );
1438 let patterns = (0..query.pattern_count())
1439 .map(|ix| {
1440 let mut config = BracketsPatternConfig::default();
1441 for setting in query.property_settings(ix) {
1442 match setting.key.as_ref() {
1443 "newline.only" => config.newline_only = true,
1444 _ => {}
1445 }
1446 }
1447 config
1448 })
1449 .collect();
1450 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1451 grammar.brackets_config = Some(BracketsConfig {
1452 query,
1453 open_capture_ix,
1454 close_capture_ix,
1455 patterns,
1456 });
1457 }
1458 Ok(self)
1459 }
1460
1461 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1462 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1463 let query = Query::new(&grammar.ts_language, source)?;
1464 let mut indent_capture_ix = None;
1465 let mut start_capture_ix = None;
1466 let mut end_capture_ix = None;
1467 let mut outdent_capture_ix = None;
1468 get_capture_indices(
1469 &query,
1470 &mut [
1471 ("indent", &mut indent_capture_ix),
1472 ("start", &mut start_capture_ix),
1473 ("end", &mut end_capture_ix),
1474 ("outdent", &mut outdent_capture_ix),
1475 ],
1476 );
1477 if let Some(indent_capture_ix) = indent_capture_ix {
1478 grammar.indents_config = Some(IndentConfig {
1479 query,
1480 indent_capture_ix,
1481 start_capture_ix,
1482 end_capture_ix,
1483 outdent_capture_ix,
1484 });
1485 }
1486 Ok(self)
1487 }
1488
1489 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1490 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1491 let query = Query::new(&grammar.ts_language, source)?;
1492 let mut language_capture_ix = None;
1493 let mut injection_language_capture_ix = None;
1494 let mut content_capture_ix = None;
1495 let mut injection_content_capture_ix = None;
1496 get_capture_indices(
1497 &query,
1498 &mut [
1499 ("language", &mut language_capture_ix),
1500 ("injection.language", &mut injection_language_capture_ix),
1501 ("content", &mut content_capture_ix),
1502 ("injection.content", &mut injection_content_capture_ix),
1503 ],
1504 );
1505 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1506 (None, Some(ix)) => Some(ix),
1507 (Some(_), Some(_)) => {
1508 anyhow::bail!("both language and injection.language captures are present");
1509 }
1510 _ => language_capture_ix,
1511 };
1512 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1513 (None, Some(ix)) => Some(ix),
1514 (Some(_), Some(_)) => {
1515 anyhow::bail!("both content and injection.content captures are present")
1516 }
1517 _ => content_capture_ix,
1518 };
1519 let patterns = (0..query.pattern_count())
1520 .map(|ix| {
1521 let mut config = InjectionPatternConfig::default();
1522 for setting in query.property_settings(ix) {
1523 match setting.key.as_ref() {
1524 "language" | "injection.language" => {
1525 config.language.clone_from(&setting.value);
1526 }
1527 "combined" | "injection.combined" => {
1528 config.combined = true;
1529 }
1530 _ => {}
1531 }
1532 }
1533 config
1534 })
1535 .collect();
1536 if let Some(content_capture_ix) = content_capture_ix {
1537 grammar.injection_config = Some(InjectionConfig {
1538 query,
1539 language_capture_ix,
1540 content_capture_ix,
1541 patterns,
1542 });
1543 }
1544 Ok(self)
1545 }
1546
1547 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1548 let query = {
1549 let grammar = self.grammar.as_ref().context("no grammar for language")?;
1550 Query::new(&grammar.ts_language, source)?
1551 };
1552
1553 let mut override_configs_by_id = HashMap::default();
1554 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1555 let mut range_is_inclusive = false;
1556 if name.starts_with('_') {
1557 continue;
1558 }
1559 if let Some(prefix) = name.strip_suffix(".inclusive") {
1560 name = prefix;
1561 range_is_inclusive = true;
1562 }
1563
1564 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1565 for server_name in &value.opt_into_language_servers {
1566 if !self
1567 .config
1568 .scope_opt_in_language_servers
1569 .contains(server_name)
1570 {
1571 util::debug_panic!(
1572 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1573 );
1574 }
1575 }
1576
1577 override_configs_by_id.insert(
1578 ix as u32,
1579 OverrideEntry {
1580 name: name.to_string(),
1581 range_is_inclusive,
1582 value,
1583 },
1584 );
1585 }
1586
1587 let referenced_override_names = self.config.overrides.keys().chain(
1588 self.config
1589 .brackets
1590 .disabled_scopes_by_bracket_ix
1591 .iter()
1592 .flatten(),
1593 );
1594
1595 for referenced_name in referenced_override_names {
1596 if !override_configs_by_id
1597 .values()
1598 .any(|entry| entry.name == *referenced_name)
1599 {
1600 anyhow::bail!(
1601 "language {:?} has overrides in config not in query: {referenced_name:?}",
1602 self.config.name
1603 );
1604 }
1605 }
1606
1607 for entry in override_configs_by_id.values_mut() {
1608 entry.value.disabled_bracket_ixs = self
1609 .config
1610 .brackets
1611 .disabled_scopes_by_bracket_ix
1612 .iter()
1613 .enumerate()
1614 .filter_map(|(ix, disabled_scope_names)| {
1615 if disabled_scope_names.contains(&entry.name) {
1616 Some(ix as u16)
1617 } else {
1618 None
1619 }
1620 })
1621 .collect();
1622 }
1623
1624 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1625
1626 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1627 grammar.override_config = Some(OverrideConfig {
1628 query,
1629 values: override_configs_by_id,
1630 });
1631 Ok(self)
1632 }
1633
1634 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1635 let grammar = self.grammar_mut().context("cannot mutate grammar")?;
1636
1637 let query = Query::new(&grammar.ts_language, source)?;
1638 let mut redaction_capture_ix = None;
1639 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1640
1641 if let Some(redaction_capture_ix) = redaction_capture_ix {
1642 grammar.redactions_config = Some(RedactionConfig {
1643 query,
1644 redaction_capture_ix,
1645 });
1646 }
1647
1648 Ok(self)
1649 }
1650
1651 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1652 Arc::get_mut(self.grammar.as_mut()?)
1653 }
1654
1655 pub fn name(&self) -> LanguageName {
1656 self.config.name.clone()
1657 }
1658
1659 pub fn code_fence_block_name(&self) -> Arc<str> {
1660 self.config
1661 .code_fence_block_name
1662 .clone()
1663 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1664 }
1665
1666 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1667 self.context_provider.clone()
1668 }
1669
1670 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1671 self.toolchain.clone()
1672 }
1673
1674 pub fn highlight_text<'a>(
1675 self: &'a Arc<Self>,
1676 text: &'a Rope,
1677 range: Range<usize>,
1678 ) -> Vec<(Range<usize>, HighlightId)> {
1679 let mut result = Vec::new();
1680 if let Some(grammar) = &self.grammar {
1681 let tree = grammar.parse_text(text, None);
1682 let captures =
1683 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1684 grammar.highlights_query.as_ref()
1685 });
1686 let highlight_maps = vec![grammar.highlight_map()];
1687 let mut offset = 0;
1688 for chunk in
1689 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1690 {
1691 let end_offset = offset + chunk.text.len();
1692 if let Some(highlight_id) = chunk.syntax_highlight_id {
1693 if !highlight_id.is_default() {
1694 result.push((offset..end_offset, highlight_id));
1695 }
1696 }
1697 offset = end_offset;
1698 }
1699 }
1700 result
1701 }
1702
1703 pub fn path_suffixes(&self) -> &[String] {
1704 &self.config.matcher.path_suffixes
1705 }
1706
1707 pub fn should_autoclose_before(&self, c: char) -> bool {
1708 c.is_whitespace() || self.config.autoclose_before.contains(c)
1709 }
1710
1711 pub fn set_theme(&self, theme: &SyntaxTheme) {
1712 if let Some(grammar) = self.grammar.as_ref() {
1713 if let Some(highlights_query) = &grammar.highlights_query {
1714 *grammar.highlight_map.lock() =
1715 HighlightMap::new(highlights_query.capture_names(), theme);
1716 }
1717 }
1718 }
1719
1720 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1721 self.grammar.as_ref()
1722 }
1723
1724 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1725 LanguageScope {
1726 language: self.clone(),
1727 override_id: None,
1728 }
1729 }
1730
1731 pub fn lsp_id(&self) -> String {
1732 self.config.name.lsp_id()
1733 }
1734
1735 pub fn prettier_parser_name(&self) -> Option<&str> {
1736 self.config.prettier_parser_name.as_deref()
1737 }
1738
1739 pub fn config(&self) -> &LanguageConfig {
1740 &self.config
1741 }
1742}
1743
1744impl LanguageScope {
1745 pub fn path_suffixes(&self) -> &[String] {
1746 &self.language.path_suffixes()
1747 }
1748
1749 pub fn language_name(&self) -> LanguageName {
1750 self.language.config.name.clone()
1751 }
1752
1753 pub fn collapsed_placeholder(&self) -> &str {
1754 self.language.config.collapsed_placeholder.as_ref()
1755 }
1756
1757 /// Returns line prefix that is inserted in e.g. line continuations or
1758 /// in `toggle comments` action.
1759 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1760 Override::as_option(
1761 self.config_override().map(|o| &o.line_comments),
1762 Some(&self.language.config.line_comments),
1763 )
1764 .map_or([].as_slice(), |e| e.as_slice())
1765 }
1766
1767 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1768 Override::as_option(
1769 self.config_override().map(|o| &o.block_comment),
1770 self.language.config.block_comment.as_ref(),
1771 )
1772 .map(|e| (&e.0, &e.1))
1773 }
1774
1775 /// Returns a list of language-specific word characters.
1776 ///
1777 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1778 /// the purpose of actions like 'move to next word end` or whole-word search.
1779 /// It additionally accounts for language's additional word characters.
1780 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1781 Override::as_option(
1782 self.config_override().map(|o| &o.word_characters),
1783 Some(&self.language.config.word_characters),
1784 )
1785 }
1786
1787 /// Returns a list of language-specific characters that are considered part of
1788 /// a completion query.
1789 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1790 Override::as_option(
1791 self.config_override()
1792 .map(|o| &o.completion_query_characters),
1793 Some(&self.language.config.completion_query_characters),
1794 )
1795 }
1796
1797 /// Returns whether to prefer snippet `label` over `new_text` to replace text when
1798 /// completion is accepted.
1799 ///
1800 /// In cases like when cursor is in string or renaming existing function,
1801 /// you don't want to expand function signature instead just want function name
1802 /// to replace existing one.
1803 pub fn prefers_label_for_snippet_in_completion(&self) -> bool {
1804 self.config_override()
1805 .and_then(|o| o.prefer_label_for_snippet)
1806 .unwrap_or(false)
1807 }
1808
1809 /// Returns config to documentation block for this language.
1810 ///
1811 /// Used for documentation styles that require a leading character on each line,
1812 /// such as the asterisk in JSDoc, Javadoc, etc.
1813 pub fn documentation(&self) -> Option<&DocumentationConfig> {
1814 self.language.config.documentation.as_ref()
1815 }
1816
1817 /// Returns a list of bracket pairs for a given language with an additional
1818 /// piece of information about whether the particular bracket pair is currently active for a given language.
1819 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1820 let mut disabled_ids = self
1821 .config_override()
1822 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1823 self.language
1824 .config
1825 .brackets
1826 .pairs
1827 .iter()
1828 .enumerate()
1829 .map(move |(ix, bracket)| {
1830 let mut is_enabled = true;
1831 if let Some(next_disabled_ix) = disabled_ids.first() {
1832 if ix == *next_disabled_ix as usize {
1833 disabled_ids = &disabled_ids[1..];
1834 is_enabled = false;
1835 }
1836 }
1837 (bracket, is_enabled)
1838 })
1839 }
1840
1841 pub fn should_autoclose_before(&self, c: char) -> bool {
1842 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1843 }
1844
1845 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1846 let config = &self.language.config;
1847 let opt_in_servers = &config.scope_opt_in_language_servers;
1848 if opt_in_servers.contains(name) {
1849 if let Some(over) = self.config_override() {
1850 over.opt_into_language_servers.contains(name)
1851 } else {
1852 false
1853 }
1854 } else {
1855 true
1856 }
1857 }
1858
1859 pub fn override_name(&self) -> Option<&str> {
1860 let id = self.override_id?;
1861 let grammar = self.language.grammar.as_ref()?;
1862 let override_config = grammar.override_config.as_ref()?;
1863 override_config.values.get(&id).map(|e| e.name.as_str())
1864 }
1865
1866 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1867 let id = self.override_id?;
1868 let grammar = self.language.grammar.as_ref()?;
1869 let override_config = grammar.override_config.as_ref()?;
1870 override_config.values.get(&id).map(|e| &e.value)
1871 }
1872}
1873
1874impl Hash for Language {
1875 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1876 self.id.hash(state)
1877 }
1878}
1879
1880impl PartialEq for Language {
1881 fn eq(&self, other: &Self) -> bool {
1882 self.id.eq(&other.id)
1883 }
1884}
1885
1886impl Eq for Language {}
1887
1888impl Debug for Language {
1889 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1890 f.debug_struct("Language")
1891 .field("name", &self.config.name)
1892 .finish()
1893 }
1894}
1895
1896impl Grammar {
1897 pub fn id(&self) -> GrammarId {
1898 self.id
1899 }
1900
1901 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1902 with_parser(|parser| {
1903 parser
1904 .set_language(&self.ts_language)
1905 .expect("incompatible grammar");
1906 let mut chunks = text.chunks_in_range(0..text.len());
1907 parser
1908 .parse_with_options(
1909 &mut move |offset, _| {
1910 chunks.seek(offset);
1911 chunks.next().unwrap_or("").as_bytes()
1912 },
1913 old_tree.as_ref(),
1914 None,
1915 )
1916 .unwrap()
1917 })
1918 }
1919
1920 pub fn highlight_map(&self) -> HighlightMap {
1921 self.highlight_map.lock().clone()
1922 }
1923
1924 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1925 let capture_id = self
1926 .highlights_query
1927 .as_ref()?
1928 .capture_index_for_name(name)?;
1929 Some(self.highlight_map.lock().get(capture_id))
1930 }
1931}
1932
1933impl CodeLabel {
1934 pub fn fallback_for_completion(
1935 item: &lsp::CompletionItem,
1936 language: Option<&Language>,
1937 ) -> Self {
1938 let highlight_id = item.kind.and_then(|kind| {
1939 let grammar = language?.grammar()?;
1940 use lsp::CompletionItemKind as Kind;
1941 match kind {
1942 Kind::CLASS => grammar.highlight_id_for_name("type"),
1943 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
1944 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
1945 Kind::ENUM => grammar
1946 .highlight_id_for_name("enum")
1947 .or_else(|| grammar.highlight_id_for_name("type")),
1948 Kind::ENUM_MEMBER => grammar
1949 .highlight_id_for_name("variant")
1950 .or_else(|| grammar.highlight_id_for_name("property")),
1951 Kind::FIELD => grammar.highlight_id_for_name("property"),
1952 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
1953 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
1954 Kind::METHOD => grammar
1955 .highlight_id_for_name("function.method")
1956 .or_else(|| grammar.highlight_id_for_name("function")),
1957 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
1958 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
1959 Kind::STRUCT => grammar.highlight_id_for_name("type"),
1960 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
1961 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
1962 _ => None,
1963 }
1964 });
1965
1966 let label = &item.label;
1967 let label_length = label.len();
1968 let runs = highlight_id
1969 .map(|highlight_id| vec![(0..label_length, highlight_id)])
1970 .unwrap_or_default();
1971 let text = if let Some(detail) = item.detail.as_deref().filter(|detail| detail != label) {
1972 format!("{label} {detail}")
1973 } else if let Some(description) = item
1974 .label_details
1975 .as_ref()
1976 .and_then(|label_details| label_details.description.as_deref())
1977 .filter(|description| description != label)
1978 {
1979 format!("{label} {description}")
1980 } else {
1981 label.clone()
1982 };
1983 Self {
1984 text,
1985 runs,
1986 filter_range: 0..label_length,
1987 }
1988 }
1989
1990 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1991 let mut result = Self {
1992 runs: Vec::new(),
1993 filter_range: 0..text.len(),
1994 text,
1995 };
1996 if let Some(filter_text) = filter_text {
1997 if let Some(ix) = result.text.find(filter_text) {
1998 result.filter_range = ix..ix + filter_text.len();
1999 }
2000 }
2001 result
2002 }
2003
2004 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
2005 let start_ix = self.text.len();
2006 self.text.push_str(text);
2007 let end_ix = self.text.len();
2008 if let Some(highlight) = highlight {
2009 self.runs.push((start_ix..end_ix, highlight));
2010 }
2011 }
2012
2013 pub fn text(&self) -> &str {
2014 self.text.as_str()
2015 }
2016
2017 pub fn filter_text(&self) -> &str {
2018 &self.text[self.filter_range.clone()]
2019 }
2020}
2021
2022impl From<String> for CodeLabel {
2023 fn from(value: String) -> Self {
2024 Self::plain(value, None)
2025 }
2026}
2027
2028impl From<&str> for CodeLabel {
2029 fn from(value: &str) -> Self {
2030 Self::plain(value.to_string(), None)
2031 }
2032}
2033
2034impl Ord for LanguageMatcher {
2035 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
2036 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
2037 self.first_line_pattern
2038 .as_ref()
2039 .map(Regex::as_str)
2040 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
2041 })
2042 }
2043}
2044
2045impl PartialOrd for LanguageMatcher {
2046 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
2047 Some(self.cmp(other))
2048 }
2049}
2050
2051impl Eq for LanguageMatcher {}
2052
2053impl PartialEq for LanguageMatcher {
2054 fn eq(&self, other: &Self) -> bool {
2055 self.path_suffixes == other.path_suffixes
2056 && self.first_line_pattern.as_ref().map(Regex::as_str)
2057 == other.first_line_pattern.as_ref().map(Regex::as_str)
2058 }
2059}
2060
2061#[cfg(any(test, feature = "test-support"))]
2062impl Default for FakeLspAdapter {
2063 fn default() -> Self {
2064 Self {
2065 name: "the-fake-language-server",
2066 capabilities: lsp::LanguageServer::full_capabilities(),
2067 initializer: None,
2068 disk_based_diagnostics_progress_token: None,
2069 initialization_options: None,
2070 disk_based_diagnostics_sources: Vec::new(),
2071 prettier_plugins: Vec::new(),
2072 language_server_binary: LanguageServerBinary {
2073 path: "/the/fake/lsp/path".into(),
2074 arguments: vec![],
2075 env: Default::default(),
2076 },
2077 label_for_completion: None,
2078 }
2079 }
2080}
2081
2082#[cfg(any(test, feature = "test-support"))]
2083#[async_trait(?Send)]
2084impl LspAdapter for FakeLspAdapter {
2085 fn name(&self) -> LanguageServerName {
2086 LanguageServerName(self.name.into())
2087 }
2088
2089 async fn check_if_user_installed(
2090 &self,
2091 _: &dyn LspAdapterDelegate,
2092 _: Arc<dyn LanguageToolchainStore>,
2093 _: &AsyncApp,
2094 ) -> Option<LanguageServerBinary> {
2095 Some(self.language_server_binary.clone())
2096 }
2097
2098 fn get_language_server_command<'a>(
2099 self: Arc<Self>,
2100 _: Arc<dyn LspAdapterDelegate>,
2101 _: Arc<dyn LanguageToolchainStore>,
2102 _: LanguageServerBinaryOptions,
2103 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2104 _: &'a mut AsyncApp,
2105 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2106 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2107 }
2108
2109 async fn fetch_latest_server_version(
2110 &self,
2111 _: &dyn LspAdapterDelegate,
2112 ) -> Result<Box<dyn 'static + Send + Any>> {
2113 unreachable!();
2114 }
2115
2116 async fn fetch_server_binary(
2117 &self,
2118 _: Box<dyn 'static + Send + Any>,
2119 _: PathBuf,
2120 _: &dyn LspAdapterDelegate,
2121 ) -> Result<LanguageServerBinary> {
2122 unreachable!();
2123 }
2124
2125 async fn cached_server_binary(
2126 &self,
2127 _: PathBuf,
2128 _: &dyn LspAdapterDelegate,
2129 ) -> Option<LanguageServerBinary> {
2130 unreachable!();
2131 }
2132
2133 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2134 self.disk_based_diagnostics_sources.clone()
2135 }
2136
2137 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2138 self.disk_based_diagnostics_progress_token.clone()
2139 }
2140
2141 async fn initialization_options(
2142 self: Arc<Self>,
2143 _: &dyn Fs,
2144 _: &Arc<dyn LspAdapterDelegate>,
2145 ) -> Result<Option<Value>> {
2146 Ok(self.initialization_options.clone())
2147 }
2148
2149 async fn label_for_completion(
2150 &self,
2151 item: &lsp::CompletionItem,
2152 language: &Arc<Language>,
2153 ) -> Option<CodeLabel> {
2154 let label_for_completion = self.label_for_completion.as_ref()?;
2155 label_for_completion(item, language)
2156 }
2157}
2158
2159fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2160 for (ix, name) in query.capture_names().iter().enumerate() {
2161 for (capture_name, index) in captures.iter_mut() {
2162 if capture_name == name {
2163 **index = Some(ix as u32);
2164 break;
2165 }
2166 }
2167 }
2168}
2169
2170pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2171 lsp::Position::new(point.row, point.column)
2172}
2173
2174pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2175 Unclipped(PointUtf16::new(point.line, point.character))
2176}
2177
2178pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2179 anyhow::ensure!(
2180 range.start <= range.end,
2181 "Inverted range provided to an LSP request: {:?}-{:?}",
2182 range.start,
2183 range.end
2184 );
2185 Ok(lsp::Range {
2186 start: point_to_lsp(range.start),
2187 end: point_to_lsp(range.end),
2188 })
2189}
2190
2191pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2192 let mut start = point_from_lsp(range.start);
2193 let mut end = point_from_lsp(range.end);
2194 if start > end {
2195 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2196 mem::swap(&mut start, &mut end);
2197 }
2198 start..end
2199}
2200
2201#[cfg(test)]
2202mod tests {
2203 use super::*;
2204 use gpui::TestAppContext;
2205
2206 #[gpui::test(iterations = 10)]
2207 async fn test_language_loading(cx: &mut TestAppContext) {
2208 let languages = LanguageRegistry::test(cx.executor());
2209 let languages = Arc::new(languages);
2210 languages.register_native_grammars([
2211 ("json", tree_sitter_json::LANGUAGE),
2212 ("rust", tree_sitter_rust::LANGUAGE),
2213 ]);
2214 languages.register_test_language(LanguageConfig {
2215 name: "JSON".into(),
2216 grammar: Some("json".into()),
2217 matcher: LanguageMatcher {
2218 path_suffixes: vec!["json".into()],
2219 ..Default::default()
2220 },
2221 ..Default::default()
2222 });
2223 languages.register_test_language(LanguageConfig {
2224 name: "Rust".into(),
2225 grammar: Some("rust".into()),
2226 matcher: LanguageMatcher {
2227 path_suffixes: vec!["rs".into()],
2228 ..Default::default()
2229 },
2230 ..Default::default()
2231 });
2232 assert_eq!(
2233 languages.language_names(),
2234 &[
2235 "JSON".to_string(),
2236 "Plain Text".to_string(),
2237 "Rust".to_string(),
2238 ]
2239 );
2240
2241 let rust1 = languages.language_for_name("Rust");
2242 let rust2 = languages.language_for_name("Rust");
2243
2244 // Ensure language is still listed even if it's being loaded.
2245 assert_eq!(
2246 languages.language_names(),
2247 &[
2248 "JSON".to_string(),
2249 "Plain Text".to_string(),
2250 "Rust".to_string(),
2251 ]
2252 );
2253
2254 let (rust1, rust2) = futures::join!(rust1, rust2);
2255 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2256
2257 // Ensure language is still listed even after loading it.
2258 assert_eq!(
2259 languages.language_names(),
2260 &[
2261 "JSON".to_string(),
2262 "Plain Text".to_string(),
2263 "Rust".to_string(),
2264 ]
2265 );
2266
2267 // Loading an unknown language returns an error.
2268 assert!(languages.language_for_name("Unknown").await.is_err());
2269 }
2270
2271 #[gpui::test]
2272 async fn test_completion_label_omits_duplicate_data() {
2273 let regular_completion_item_1 = lsp::CompletionItem {
2274 label: "regular1".to_string(),
2275 detail: Some("detail1".to_string()),
2276 label_details: Some(lsp::CompletionItemLabelDetails {
2277 detail: None,
2278 description: Some("description 1".to_string()),
2279 }),
2280 ..lsp::CompletionItem::default()
2281 };
2282
2283 let regular_completion_item_2 = lsp::CompletionItem {
2284 label: "regular2".to_string(),
2285 label_details: Some(lsp::CompletionItemLabelDetails {
2286 detail: None,
2287 description: Some("description 2".to_string()),
2288 }),
2289 ..lsp::CompletionItem::default()
2290 };
2291
2292 let completion_item_with_duplicate_detail_and_proper_description = lsp::CompletionItem {
2293 detail: Some(regular_completion_item_1.label.clone()),
2294 ..regular_completion_item_1.clone()
2295 };
2296
2297 let completion_item_with_duplicate_detail = lsp::CompletionItem {
2298 detail: Some(regular_completion_item_1.label.clone()),
2299 label_details: None,
2300 ..regular_completion_item_1.clone()
2301 };
2302
2303 let completion_item_with_duplicate_description = lsp::CompletionItem {
2304 label_details: Some(lsp::CompletionItemLabelDetails {
2305 detail: None,
2306 description: Some(regular_completion_item_2.label.clone()),
2307 }),
2308 ..regular_completion_item_2.clone()
2309 };
2310
2311 assert_eq!(
2312 CodeLabel::fallback_for_completion(®ular_completion_item_1, None).text,
2313 format!(
2314 "{} {}",
2315 regular_completion_item_1.label,
2316 regular_completion_item_1.detail.unwrap()
2317 ),
2318 "LSP completion items with both detail and label_details.description should prefer detail"
2319 );
2320 assert_eq!(
2321 CodeLabel::fallback_for_completion(®ular_completion_item_2, None).text,
2322 format!(
2323 "{} {}",
2324 regular_completion_item_2.label,
2325 regular_completion_item_2
2326 .label_details
2327 .as_ref()
2328 .unwrap()
2329 .description
2330 .as_ref()
2331 .unwrap()
2332 ),
2333 "LSP completion items without detail but with label_details.description should use that"
2334 );
2335 assert_eq!(
2336 CodeLabel::fallback_for_completion(
2337 &completion_item_with_duplicate_detail_and_proper_description,
2338 None
2339 )
2340 .text,
2341 format!(
2342 "{} {}",
2343 regular_completion_item_1.label,
2344 regular_completion_item_1
2345 .label_details
2346 .as_ref()
2347 .unwrap()
2348 .description
2349 .as_ref()
2350 .unwrap()
2351 ),
2352 "LSP completion items with both detail and label_details.description should prefer description only if the detail duplicates the completion label"
2353 );
2354 assert_eq!(
2355 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_detail, None).text,
2356 regular_completion_item_1.label,
2357 "LSP completion items with duplicate label and detail, should omit the detail"
2358 );
2359 assert_eq!(
2360 CodeLabel::fallback_for_completion(&completion_item_with_duplicate_description, None)
2361 .text,
2362 regular_completion_item_2.label,
2363 "LSP completion items with duplicate label and detail, should omit the detail"
2364 );
2365 }
2366}