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 outline;
15pub mod proto;
16mod syntax_map;
17mod task_context;
18
19#[cfg(test)]
20mod buffer_tests;
21pub mod markdown;
22
23use anyhow::{anyhow, Context, Result};
24use async_trait::async_trait;
25use collections::{HashMap, HashSet};
26use futures::Future;
27use gpui::{AppContext, AsyncAppContext, Model, Task};
28pub use highlight_map::HighlightMap;
29use lazy_static::lazy_static;
30use lsp::{CodeActionKind, LanguageServerBinary};
31use parking_lot::Mutex;
32use regex::Regex;
33use schemars::{
34 gen::SchemaGenerator,
35 schema::{InstanceType, Schema, SchemaObject},
36 JsonSchema,
37};
38use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
39use serde_json::Value;
40use smol::future::FutureExt as _;
41use std::{
42 any::Any,
43 cell::RefCell,
44 ffi::OsStr,
45 fmt::Debug,
46 hash::Hash,
47 mem,
48 ops::Range,
49 path::{Path, PathBuf},
50 pin::Pin,
51 str,
52 sync::{
53 atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
54 Arc,
55 },
56};
57use syntax_map::SyntaxSnapshot;
58pub use task_context::{
59 ContextProvider, ContextProviderWithTasks, LanguageSource, SymbolContextProvider,
60};
61use theme::SyntaxTheme;
62use tree_sitter::{self, wasmtime, Query, WasmStore};
63use util::http::HttpClient;
64
65pub use buffer::Operation;
66pub use buffer::*;
67pub use diagnostic_set::DiagnosticEntry;
68pub use language_registry::{
69 LanguageNotFound, LanguageQueries, LanguageRegistry, LanguageServerBinaryStatus,
70 PendingLanguageServer, QUERY_FILENAME_PREFIXES,
71};
72pub use lsp::LanguageServerId;
73pub use outline::{Outline, OutlineItem};
74pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer};
75pub use text::LineEnding;
76pub use tree_sitter::{Parser, Tree};
77
78/// Initializes the `language` crate.
79///
80/// This should be called before making use of items from the create.
81pub fn init(cx: &mut AppContext) {
82 language_settings::init(cx);
83}
84
85thread_local! {
86 static PARSER: RefCell<Parser> = {
87 let mut parser = Parser::new();
88 parser.set_wasm_store(WasmStore::new(WASM_ENGINE.clone()).unwrap()).unwrap();
89 RefCell::new(parser)
90 };
91}
92
93lazy_static! {
94 static ref NEXT_LANGUAGE_ID: AtomicUsize = Default::default();
95 static ref NEXT_GRAMMAR_ID: AtomicUsize = Default::default();
96 static ref WASM_ENGINE: wasmtime::Engine = {
97 wasmtime::Engine::new(&wasmtime::Config::new()).unwrap()
98 };
99
100 /// A shared grammar for plain text, exposed for reuse by downstream crates.
101 pub static ref PLAIN_TEXT: Arc<Language> = Arc::new(Language::new(
102 LanguageConfig {
103 name: "Plain Text".into(),
104 ..Default::default()
105 },
106 None,
107 ));
108}
109
110/// Types that represent a position in a buffer, and can be converted into
111/// an LSP position, to send to a language server.
112pub trait ToLspPosition {
113 /// Converts the value into an LSP position.
114 fn to_lsp_position(self) -> lsp::Position;
115}
116
117/// A name of a language server.
118#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
119pub struct LanguageServerName(pub Arc<str>);
120
121#[derive(Debug, Clone, PartialEq, Eq, Hash)]
122pub struct Location {
123 pub buffer: Model<Buffer>,
124 pub range: Range<Anchor>,
125}
126
127/// Represents a Language Server, with certain cached sync properties.
128/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
129/// once at startup, and caches the results.
130pub struct CachedLspAdapter {
131 pub name: LanguageServerName,
132 pub disk_based_diagnostic_sources: Vec<String>,
133 pub disk_based_diagnostics_progress_token: Option<String>,
134 pub language_ids: HashMap<String, String>,
135 pub adapter: Arc<dyn LspAdapter>,
136 pub reinstall_attempt_count: AtomicU64,
137 /// Indicates whether this language server is the primary language server
138 /// for a given language. Currently, most LSP-backed features only work
139 /// with one language server, so one server needs to be primary.
140 pub is_primary: bool,
141 cached_binary: futures::lock::Mutex<Option<LanguageServerBinary>>,
142}
143
144impl CachedLspAdapter {
145 pub fn new(adapter: Arc<dyn LspAdapter>, is_primary: bool) -> Arc<Self> {
146 let name = adapter.name();
147 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
148 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
149 let language_ids = adapter.language_ids();
150
151 Arc::new(CachedLspAdapter {
152 name,
153 disk_based_diagnostic_sources,
154 disk_based_diagnostics_progress_token,
155 language_ids,
156 adapter,
157 is_primary,
158 cached_binary: Default::default(),
159 reinstall_attempt_count: AtomicU64::new(0),
160 })
161 }
162
163 pub async fn get_language_server_command(
164 self: Arc<Self>,
165 language: Arc<Language>,
166 container_dir: Arc<Path>,
167 delegate: Arc<dyn LspAdapterDelegate>,
168 cx: &mut AsyncAppContext,
169 ) -> Result<LanguageServerBinary> {
170 let cached_binary = self.cached_binary.lock().await;
171 self.adapter
172 .clone()
173 .get_language_server_command(language, container_dir, delegate, cached_binary, cx)
174 .await
175 }
176
177 pub fn will_start_server(
178 &self,
179 delegate: &Arc<dyn LspAdapterDelegate>,
180 cx: &mut AsyncAppContext,
181 ) -> Option<Task<Result<()>>> {
182 self.adapter.will_start_server(delegate, cx)
183 }
184
185 pub fn can_be_reinstalled(&self) -> bool {
186 self.adapter.can_be_reinstalled()
187 }
188
189 pub async fn installation_test_binary(
190 &self,
191 container_dir: PathBuf,
192 ) -> Option<LanguageServerBinary> {
193 self.adapter.installation_test_binary(container_dir).await
194 }
195
196 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
197 self.adapter.code_action_kinds()
198 }
199
200 pub fn workspace_configuration(&self, workspace_root: &Path, cx: &mut AppContext) -> Value {
201 self.adapter.workspace_configuration(workspace_root, cx)
202 }
203
204 pub fn process_diagnostics(&self, params: &mut lsp::PublishDiagnosticsParams) {
205 self.adapter.process_diagnostics(params)
206 }
207
208 pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
209 self.adapter.process_completions(completion_items).await
210 }
211
212 pub async fn labels_for_completions(
213 &self,
214 completion_items: &[lsp::CompletionItem],
215 language: &Arc<Language>,
216 ) -> Vec<Option<CodeLabel>> {
217 self.adapter
218 .labels_for_completions(completion_items, language)
219 .await
220 }
221
222 pub async fn labels_for_symbols(
223 &self,
224 symbols: &[(String, lsp::SymbolKind)],
225 language: &Arc<Language>,
226 ) -> Vec<Option<CodeLabel>> {
227 self.adapter.labels_for_symbols(symbols, language).await
228 }
229
230 #[cfg(any(test, feature = "test-support"))]
231 fn as_fake(&self) -> Option<&FakeLspAdapter> {
232 self.adapter.as_fake()
233 }
234}
235
236/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
237// e.g. to display a notification or fetch data from the web.
238#[async_trait]
239pub trait LspAdapterDelegate: Send + Sync {
240 fn show_notification(&self, message: &str, cx: &mut AppContext);
241 fn http_client(&self) -> Arc<dyn HttpClient>;
242 fn update_status(&self, language: LanguageServerName, status: LanguageServerBinaryStatus);
243
244 async fn which(&self, command: &OsStr) -> Option<PathBuf>;
245 async fn shell_env(&self) -> HashMap<String, String>;
246 async fn read_text_file(&self, path: PathBuf) -> Result<String>;
247}
248
249#[async_trait(?Send)]
250pub trait LspAdapter: 'static + Send + Sync {
251 fn name(&self) -> LanguageServerName;
252
253 fn get_language_server_command<'a>(
254 self: Arc<Self>,
255 language: Arc<Language>,
256 container_dir: Arc<Path>,
257 delegate: Arc<dyn LspAdapterDelegate>,
258 mut cached_binary: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
259 cx: &'a mut AsyncAppContext,
260 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
261 async move {
262 // First we check whether the adapter can give us a user-installed binary.
263 // If so, we do *not* want to cache that, because each worktree might give us a different
264 // binary:
265 //
266 // worktree 1: user-installed at `.bin/gopls`
267 // worktree 2: user-installed at `~/bin/gopls`
268 // worktree 3: no gopls found in PATH -> fallback to Zed installation
269 //
270 // We only want to cache when we fall back to the global one,
271 // because we don't want to download and overwrite our global one
272 // for each worktree we might have open.
273 if let Some(binary) = self.check_if_user_installed(delegate.as_ref(), cx).await {
274 log::info!(
275 "found user-installed language server for {}. path: {:?}, arguments: {:?}",
276 language.name(),
277 binary.path,
278 binary.arguments
279 );
280 return Ok(binary);
281 }
282
283 if let Some(cached_binary) = cached_binary.as_ref() {
284 return Ok(cached_binary.clone());
285 }
286
287 if !container_dir.exists() {
288 smol::fs::create_dir_all(&container_dir)
289 .await
290 .context("failed to create container directory")?;
291 }
292
293 let mut binary = try_fetch_server_binary(self.as_ref(), &delegate, container_dir.to_path_buf(), cx).await;
294
295 if let Err(error) = binary.as_ref() {
296 if let Some(prev_downloaded_binary) = self
297 .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
298 .await
299 {
300 log::info!(
301 "failed to fetch newest version of language server {:?}. falling back to using {:?}",
302 self.name(),
303 prev_downloaded_binary.path
304 );
305 binary = Ok(prev_downloaded_binary);
306 } else {
307 delegate.update_status(
308 self.name(),
309 LanguageServerBinaryStatus::Failed {
310 error: format!("{error:?}"),
311 },
312 );
313 }
314 }
315
316 if let Ok(binary) = &binary {
317 *cached_binary = Some(binary.clone());
318 }
319
320 binary
321 }
322 .boxed_local()
323 }
324
325 async fn check_if_user_installed(
326 &self,
327 _: &dyn LspAdapterDelegate,
328 _: &AsyncAppContext,
329 ) -> Option<LanguageServerBinary> {
330 None
331 }
332
333 async fn fetch_latest_server_version(
334 &self,
335 delegate: &dyn LspAdapterDelegate,
336 ) -> Result<Box<dyn 'static + Send + Any>>;
337
338 fn will_fetch_server(
339 &self,
340 _: &Arc<dyn LspAdapterDelegate>,
341 _: &mut AsyncAppContext,
342 ) -> Option<Task<Result<()>>> {
343 None
344 }
345
346 fn will_start_server(
347 &self,
348 _: &Arc<dyn LspAdapterDelegate>,
349 _: &mut AsyncAppContext,
350 ) -> Option<Task<Result<()>>> {
351 None
352 }
353
354 async fn fetch_server_binary(
355 &self,
356 latest_version: Box<dyn 'static + Send + Any>,
357 container_dir: PathBuf,
358 delegate: &dyn LspAdapterDelegate,
359 ) -> Result<LanguageServerBinary>;
360
361 async fn cached_server_binary(
362 &self,
363 container_dir: PathBuf,
364 delegate: &dyn LspAdapterDelegate,
365 ) -> Option<LanguageServerBinary>;
366
367 /// Returns `true` if a language server can be reinstalled.
368 ///
369 /// If language server initialization fails, a reinstallation will be attempted unless the value returned from this method is `false`.
370 ///
371 /// Implementations that rely on software already installed on user's system
372 /// should have [`can_be_reinstalled`](Self::can_be_reinstalled) return `false`.
373 fn can_be_reinstalled(&self) -> bool {
374 true
375 }
376
377 async fn installation_test_binary(
378 &self,
379 container_dir: PathBuf,
380 ) -> Option<LanguageServerBinary>;
381
382 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
383
384 /// Post-processes completions provided by the language server.
385 async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
386
387 async fn labels_for_completions(
388 &self,
389 completions: &[lsp::CompletionItem],
390 language: &Arc<Language>,
391 ) -> Vec<Option<CodeLabel>> {
392 let mut labels = Vec::new();
393 for (ix, completion) in completions.into_iter().enumerate() {
394 let label = self.label_for_completion(completion, language).await;
395 if let Some(label) = label {
396 labels.resize(ix + 1, None);
397 *labels.last_mut().unwrap() = Some(label);
398 }
399 }
400 labels
401 }
402
403 async fn label_for_completion(
404 &self,
405 _: &lsp::CompletionItem,
406 _: &Arc<Language>,
407 ) -> Option<CodeLabel> {
408 None
409 }
410
411 async fn labels_for_symbols(
412 &self,
413 symbols: &[(String, lsp::SymbolKind)],
414 language: &Arc<Language>,
415 ) -> Vec<Option<CodeLabel>> {
416 let mut labels = Vec::new();
417 for (ix, (name, kind)) in symbols.into_iter().enumerate() {
418 let label = self.label_for_symbol(name, *kind, language).await;
419 if let Some(label) = label {
420 labels.resize(ix + 1, None);
421 *labels.last_mut().unwrap() = Some(label);
422 }
423 }
424 labels
425 }
426
427 async fn label_for_symbol(
428 &self,
429 _: &str,
430 _: lsp::SymbolKind,
431 _: &Arc<Language>,
432 ) -> Option<CodeLabel> {
433 None
434 }
435
436 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
437 async fn initialization_options(
438 self: Arc<Self>,
439 _: &Arc<dyn LspAdapterDelegate>,
440 ) -> Result<Option<Value>> {
441 Ok(None)
442 }
443
444 fn workspace_configuration(&self, _workspace_root: &Path, _cx: &mut AppContext) -> Value {
445 serde_json::json!({})
446 }
447
448 /// Returns a list of code actions supported by a given LspAdapter
449 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
450 Some(vec![
451 CodeActionKind::EMPTY,
452 CodeActionKind::QUICKFIX,
453 CodeActionKind::REFACTOR,
454 CodeActionKind::REFACTOR_EXTRACT,
455 CodeActionKind::SOURCE,
456 ])
457 }
458
459 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
460 Default::default()
461 }
462
463 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
464 None
465 }
466
467 fn language_ids(&self) -> HashMap<String, String> {
468 Default::default()
469 }
470
471 #[cfg(any(test, feature = "test-support"))]
472 fn as_fake(&self) -> Option<&FakeLspAdapter> {
473 None
474 }
475}
476
477async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
478 adapter: &L,
479 delegate: &Arc<dyn LspAdapterDelegate>,
480 container_dir: PathBuf,
481 cx: &mut AsyncAppContext,
482) -> Result<LanguageServerBinary> {
483 if let Some(task) = adapter.will_fetch_server(delegate, cx) {
484 task.await?;
485 }
486
487 let name = adapter.name();
488 log::info!("fetching latest version of language server {:?}", name.0);
489 delegate.update_status(name.clone(), LanguageServerBinaryStatus::CheckingForUpdate);
490 let latest_version = adapter
491 .fetch_latest_server_version(delegate.as_ref())
492 .await?;
493
494 log::info!("downloading language server {:?}", name.0);
495 delegate.update_status(adapter.name(), LanguageServerBinaryStatus::Downloading);
496 let binary = adapter
497 .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
498 .await;
499
500 delegate.update_status(name.clone(), LanguageServerBinaryStatus::None);
501 binary
502}
503
504#[derive(Clone, Debug, PartialEq, Eq)]
505pub struct CodeLabel {
506 /// The text to display.
507 pub text: String,
508 /// Syntax highlighting runs.
509 pub runs: Vec<(Range<usize>, HighlightId)>,
510 /// The portion of the text that should be used in fuzzy filtering.
511 pub filter_range: Range<usize>,
512}
513
514#[derive(Clone, Deserialize, JsonSchema)]
515pub struct LanguageConfig {
516 /// Human-readable name of the language.
517 pub name: Arc<str>,
518 /// The name of this language for a Markdown code fence block
519 pub code_fence_block_name: Option<Arc<str>>,
520 // The name of the grammar in a WASM bundle (experimental).
521 pub grammar: Option<Arc<str>>,
522 /// The criteria for matching this language to a given file.
523 #[serde(flatten)]
524 pub matcher: LanguageMatcher,
525 /// List of bracket types in a language.
526 #[serde(default)]
527 #[schemars(schema_with = "bracket_pair_config_json_schema")]
528 pub brackets: BracketPairConfig,
529 /// If set to true, auto indentation uses last non empty line to determine
530 /// the indentation level for a new line.
531 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
532 pub auto_indent_using_last_non_empty_line: bool,
533 /// A regex that is used to determine whether the indentation level should be
534 /// increased in the following line.
535 #[serde(default, deserialize_with = "deserialize_regex")]
536 #[schemars(schema_with = "regex_json_schema")]
537 pub increase_indent_pattern: Option<Regex>,
538 /// A regex that is used to determine whether the indentation level should be
539 /// decreased in the following line.
540 #[serde(default, deserialize_with = "deserialize_regex")]
541 #[schemars(schema_with = "regex_json_schema")]
542 pub decrease_indent_pattern: Option<Regex>,
543 /// A list of characters that trigger the automatic insertion of a closing
544 /// bracket when they immediately precede the point where an opening
545 /// bracket is inserted.
546 #[serde(default)]
547 pub autoclose_before: String,
548 /// A placeholder used internally by Semantic Index.
549 #[serde(default)]
550 pub collapsed_placeholder: String,
551 /// A line comment string that is inserted in e.g. `toggle comments` action.
552 /// A language can have multiple flavours of line comments. All of the provided line comments are
553 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
554 #[serde(default)]
555 pub line_comments: Vec<Arc<str>>,
556 /// Starting and closing characters of a block comment.
557 #[serde(default)]
558 pub block_comment: Option<(Arc<str>, Arc<str>)>,
559 /// A list of language servers that are allowed to run on subranges of a given language.
560 #[serde(default)]
561 pub scope_opt_in_language_servers: Vec<String>,
562 #[serde(default)]
563 pub overrides: HashMap<String, LanguageConfigOverride>,
564 /// A list of characters that Zed should treat as word characters for the
565 /// purpose of features that operate on word boundaries, like 'move to next word end'
566 /// or a whole-word search in buffer search.
567 #[serde(default)]
568 pub word_characters: HashSet<char>,
569 /// The name of a Prettier parser that should be used for this language.
570 #[serde(default)]
571 pub prettier_parser_name: Option<String>,
572 /// The names of any Prettier plugins that should be used for this language.
573 #[serde(default)]
574 pub prettier_plugins: Vec<Arc<str>>,
575}
576
577#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
578pub struct LanguageMatcher {
579 /// 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`.
580 #[serde(default)]
581 pub path_suffixes: Vec<String>,
582 /// A regex pattern that determines whether the language should be assigned to a file or not.
583 #[serde(
584 default,
585 serialize_with = "serialize_regex",
586 deserialize_with = "deserialize_regex"
587 )]
588 #[schemars(schema_with = "regex_json_schema")]
589 pub first_line_pattern: Option<Regex>,
590}
591
592/// Represents a language for the given range. Some languages (e.g. HTML)
593/// interleave several languages together, thus a single buffer might actually contain
594/// several nested scopes.
595#[derive(Clone, Debug)]
596pub struct LanguageScope {
597 language: Arc<Language>,
598 override_id: Option<u32>,
599}
600
601#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
602pub struct LanguageConfigOverride {
603 #[serde(default)]
604 pub line_comments: Override<Vec<Arc<str>>>,
605 #[serde(default)]
606 pub block_comment: Override<(Arc<str>, Arc<str>)>,
607 #[serde(skip_deserializing)]
608 #[schemars(skip)]
609 pub disabled_bracket_ixs: Vec<u16>,
610 #[serde(default)]
611 pub word_characters: Override<HashSet<char>>,
612 #[serde(default)]
613 pub opt_into_language_servers: Vec<String>,
614}
615
616#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
617#[serde(untagged)]
618pub enum Override<T> {
619 Remove { remove: bool },
620 Set(T),
621}
622
623impl<T> Default for Override<T> {
624 fn default() -> Self {
625 Override::Remove { remove: false }
626 }
627}
628
629impl<T> Override<T> {
630 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
631 match this {
632 Some(Self::Set(value)) => Some(value),
633 Some(Self::Remove { remove: true }) => None,
634 Some(Self::Remove { remove: false }) | None => original,
635 }
636 }
637}
638
639impl Default for LanguageConfig {
640 fn default() -> Self {
641 Self {
642 name: "".into(),
643 code_fence_block_name: None,
644 grammar: None,
645 matcher: LanguageMatcher::default(),
646 brackets: Default::default(),
647 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
648 increase_indent_pattern: Default::default(),
649 decrease_indent_pattern: Default::default(),
650 autoclose_before: Default::default(),
651 line_comments: Default::default(),
652 block_comment: Default::default(),
653 scope_opt_in_language_servers: Default::default(),
654 overrides: Default::default(),
655 word_characters: Default::default(),
656 prettier_parser_name: None,
657 prettier_plugins: Default::default(),
658 collapsed_placeholder: Default::default(),
659 }
660 }
661}
662
663fn auto_indent_using_last_non_empty_line_default() -> bool {
664 true
665}
666
667fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
668 let source = Option::<String>::deserialize(d)?;
669 if let Some(source) = source {
670 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
671 } else {
672 Ok(None)
673 }
674}
675
676fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
677 Schema::Object(SchemaObject {
678 instance_type: Some(InstanceType::String.into()),
679 ..Default::default()
680 })
681}
682
683fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
684where
685 S: Serializer,
686{
687 match regex {
688 Some(regex) => serializer.serialize_str(regex.as_str()),
689 None => serializer.serialize_none(),
690 }
691}
692
693#[doc(hidden)]
694#[cfg(any(test, feature = "test-support"))]
695pub struct FakeLspAdapter {
696 pub name: &'static str,
697 pub initialization_options: Option<Value>,
698 pub capabilities: lsp::ServerCapabilities,
699 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
700 pub disk_based_diagnostics_progress_token: Option<String>,
701 pub disk_based_diagnostics_sources: Vec<String>,
702 pub prettier_plugins: Vec<&'static str>,
703 pub language_server_binary: LanguageServerBinary,
704}
705
706/// Configuration of handling bracket pairs for a given language.
707///
708/// This struct includes settings for defining which pairs of characters are considered brackets and
709/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
710#[derive(Clone, Debug, Default, JsonSchema)]
711pub struct BracketPairConfig {
712 /// A list of character pairs that should be treated as brackets in the context of a given language.
713 pub pairs: Vec<BracketPair>,
714 /// A list of tree-sitter scopes for which a given bracket should not be active.
715 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
716 #[schemars(skip)]
717 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
718}
719
720fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
721 Option::<Vec<BracketPairContent>>::json_schema(gen)
722}
723
724#[derive(Deserialize, JsonSchema)]
725pub struct BracketPairContent {
726 #[serde(flatten)]
727 pub bracket_pair: BracketPair,
728 #[serde(default)]
729 pub not_in: Vec<String>,
730}
731
732impl<'de> Deserialize<'de> for BracketPairConfig {
733 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
734 where
735 D: Deserializer<'de>,
736 {
737 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
738 let mut brackets = Vec::with_capacity(result.len());
739 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
740 for entry in result {
741 brackets.push(entry.bracket_pair);
742 disabled_scopes_by_bracket_ix.push(entry.not_in);
743 }
744
745 Ok(BracketPairConfig {
746 pairs: brackets,
747 disabled_scopes_by_bracket_ix,
748 })
749 }
750}
751
752/// Describes a single bracket pair and how an editor should react to e.g. inserting
753/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
754#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
755pub struct BracketPair {
756 /// Starting substring for a bracket.
757 pub start: String,
758 /// Ending substring for a bracket.
759 pub end: String,
760 /// True if `end` should be automatically inserted right after `start` characters.
761 pub close: bool,
762 /// True if an extra newline should be inserted while the cursor is in the middle
763 /// of that bracket pair.
764 pub newline: bool,
765}
766
767#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
768pub(crate) struct LanguageId(usize);
769
770impl LanguageId {
771 pub(crate) fn new() -> Self {
772 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
773 }
774}
775
776pub struct Language {
777 pub(crate) id: LanguageId,
778 pub(crate) config: LanguageConfig,
779 pub(crate) grammar: Option<Arc<Grammar>>,
780 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
781}
782
783#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
784pub struct GrammarId(pub usize);
785
786impl GrammarId {
787 pub(crate) fn new() -> Self {
788 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
789 }
790}
791
792pub struct Grammar {
793 id: GrammarId,
794 pub ts_language: tree_sitter::Language,
795 pub(crate) error_query: Query,
796 pub(crate) highlights_query: Option<Query>,
797 pub(crate) brackets_config: Option<BracketConfig>,
798 pub(crate) redactions_config: Option<RedactionConfig>,
799 pub(crate) indents_config: Option<IndentConfig>,
800 pub outline_config: Option<OutlineConfig>,
801 pub embedding_config: Option<EmbeddingConfig>,
802 pub(crate) injection_config: Option<InjectionConfig>,
803 pub(crate) override_config: Option<OverrideConfig>,
804 pub(crate) highlight_map: Mutex<HighlightMap>,
805}
806
807struct IndentConfig {
808 query: Query,
809 indent_capture_ix: u32,
810 start_capture_ix: Option<u32>,
811 end_capture_ix: Option<u32>,
812 outdent_capture_ix: Option<u32>,
813}
814
815pub struct OutlineConfig {
816 pub query: Query,
817 pub item_capture_ix: u32,
818 pub name_capture_ix: u32,
819 pub context_capture_ix: Option<u32>,
820 pub extra_context_capture_ix: Option<u32>,
821}
822
823#[derive(Debug)]
824pub struct EmbeddingConfig {
825 pub query: Query,
826 pub item_capture_ix: u32,
827 pub name_capture_ix: Option<u32>,
828 pub context_capture_ix: Option<u32>,
829 pub collapse_capture_ix: Option<u32>,
830 pub keep_capture_ix: Option<u32>,
831}
832
833struct InjectionConfig {
834 query: Query,
835 content_capture_ix: u32,
836 language_capture_ix: Option<u32>,
837 patterns: Vec<InjectionPatternConfig>,
838}
839
840struct RedactionConfig {
841 pub query: Query,
842 pub redaction_capture_ix: u32,
843}
844
845struct OverrideConfig {
846 query: Query,
847 values: HashMap<u32, (String, LanguageConfigOverride)>,
848}
849
850#[derive(Default, Clone)]
851struct InjectionPatternConfig {
852 language: Option<Box<str>>,
853 combined: bool,
854}
855
856struct BracketConfig {
857 query: Query,
858 open_capture_ix: u32,
859 close_capture_ix: u32,
860}
861
862impl Language {
863 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
864 Self::new_with_id(LanguageId::new(), config, ts_language)
865 }
866
867 fn new_with_id(
868 id: LanguageId,
869 config: LanguageConfig,
870 ts_language: Option<tree_sitter::Language>,
871 ) -> Self {
872 Self {
873 id,
874 config,
875 grammar: ts_language.map(|ts_language| {
876 Arc::new(Grammar {
877 id: GrammarId::new(),
878 highlights_query: None,
879 brackets_config: None,
880 outline_config: None,
881 embedding_config: None,
882 indents_config: None,
883 injection_config: None,
884 override_config: None,
885 redactions_config: None,
886 error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
887 ts_language,
888 highlight_map: Default::default(),
889 })
890 }),
891 context_provider: None,
892 }
893 }
894
895 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
896 self.context_provider = provider;
897 self
898 }
899
900 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
901 if let Some(query) = queries.highlights {
902 self = self
903 .with_highlights_query(query.as_ref())
904 .context("Error loading highlights query")?;
905 }
906 if let Some(query) = queries.brackets {
907 self = self
908 .with_brackets_query(query.as_ref())
909 .context("Error loading brackets query")?;
910 }
911 if let Some(query) = queries.indents {
912 self = self
913 .with_indents_query(query.as_ref())
914 .context("Error loading indents query")?;
915 }
916 if let Some(query) = queries.outline {
917 self = self
918 .with_outline_query(query.as_ref())
919 .context("Error loading outline query")?;
920 }
921 if let Some(query) = queries.embedding {
922 self = self
923 .with_embedding_query(query.as_ref())
924 .context("Error loading embedding query")?;
925 }
926 if let Some(query) = queries.injections {
927 self = self
928 .with_injection_query(query.as_ref())
929 .context("Error loading injection query")?;
930 }
931 if let Some(query) = queries.overrides {
932 self = self
933 .with_override_query(query.as_ref())
934 .context("Error loading override query")?;
935 }
936 if let Some(query) = queries.redactions {
937 self = self
938 .with_redaction_query(query.as_ref())
939 .context("Error loading redaction query")?;
940 }
941 Ok(self)
942 }
943
944 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
945 let grammar = self
946 .grammar_mut()
947 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
948 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
949 Ok(self)
950 }
951
952 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
953 let grammar = self
954 .grammar_mut()
955 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
956 let query = Query::new(&grammar.ts_language, source)?;
957 let mut item_capture_ix = None;
958 let mut name_capture_ix = None;
959 let mut context_capture_ix = None;
960 let mut extra_context_capture_ix = None;
961 get_capture_indices(
962 &query,
963 &mut [
964 ("item", &mut item_capture_ix),
965 ("name", &mut name_capture_ix),
966 ("context", &mut context_capture_ix),
967 ("context.extra", &mut extra_context_capture_ix),
968 ],
969 );
970 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
971 grammar.outline_config = Some(OutlineConfig {
972 query,
973 item_capture_ix,
974 name_capture_ix,
975 context_capture_ix,
976 extra_context_capture_ix,
977 });
978 }
979 Ok(self)
980 }
981
982 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
983 let grammar = self
984 .grammar_mut()
985 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
986 let query = Query::new(&grammar.ts_language, source)?;
987 let mut item_capture_ix = None;
988 let mut name_capture_ix = None;
989 let mut context_capture_ix = None;
990 let mut collapse_capture_ix = None;
991 let mut keep_capture_ix = None;
992 get_capture_indices(
993 &query,
994 &mut [
995 ("item", &mut item_capture_ix),
996 ("name", &mut name_capture_ix),
997 ("context", &mut context_capture_ix),
998 ("keep", &mut keep_capture_ix),
999 ("collapse", &mut collapse_capture_ix),
1000 ],
1001 );
1002 if let Some(item_capture_ix) = item_capture_ix {
1003 grammar.embedding_config = Some(EmbeddingConfig {
1004 query,
1005 item_capture_ix,
1006 name_capture_ix,
1007 context_capture_ix,
1008 collapse_capture_ix,
1009 keep_capture_ix,
1010 });
1011 }
1012 Ok(self)
1013 }
1014
1015 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1016 let grammar = self
1017 .grammar_mut()
1018 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1019 let query = Query::new(&grammar.ts_language, source)?;
1020 let mut open_capture_ix = None;
1021 let mut close_capture_ix = None;
1022 get_capture_indices(
1023 &query,
1024 &mut [
1025 ("open", &mut open_capture_ix),
1026 ("close", &mut close_capture_ix),
1027 ],
1028 );
1029 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1030 grammar.brackets_config = Some(BracketConfig {
1031 query,
1032 open_capture_ix,
1033 close_capture_ix,
1034 });
1035 }
1036 Ok(self)
1037 }
1038
1039 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1040 let grammar = self
1041 .grammar_mut()
1042 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1043 let query = Query::new(&grammar.ts_language, source)?;
1044 let mut indent_capture_ix = None;
1045 let mut start_capture_ix = None;
1046 let mut end_capture_ix = None;
1047 let mut outdent_capture_ix = None;
1048 get_capture_indices(
1049 &query,
1050 &mut [
1051 ("indent", &mut indent_capture_ix),
1052 ("start", &mut start_capture_ix),
1053 ("end", &mut end_capture_ix),
1054 ("outdent", &mut outdent_capture_ix),
1055 ],
1056 );
1057 if let Some(indent_capture_ix) = indent_capture_ix {
1058 grammar.indents_config = Some(IndentConfig {
1059 query,
1060 indent_capture_ix,
1061 start_capture_ix,
1062 end_capture_ix,
1063 outdent_capture_ix,
1064 });
1065 }
1066 Ok(self)
1067 }
1068
1069 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1070 let grammar = self
1071 .grammar_mut()
1072 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1073 let query = Query::new(&grammar.ts_language, source)?;
1074 let mut language_capture_ix = None;
1075 let mut content_capture_ix = None;
1076 get_capture_indices(
1077 &query,
1078 &mut [
1079 ("language", &mut language_capture_ix),
1080 ("content", &mut content_capture_ix),
1081 ],
1082 );
1083 let patterns = (0..query.pattern_count())
1084 .map(|ix| {
1085 let mut config = InjectionPatternConfig::default();
1086 for setting in query.property_settings(ix) {
1087 match setting.key.as_ref() {
1088 "language" => {
1089 config.language = setting.value.clone();
1090 }
1091 "combined" => {
1092 config.combined = true;
1093 }
1094 _ => {}
1095 }
1096 }
1097 config
1098 })
1099 .collect();
1100 if let Some(content_capture_ix) = content_capture_ix {
1101 grammar.injection_config = Some(InjectionConfig {
1102 query,
1103 language_capture_ix,
1104 content_capture_ix,
1105 patterns,
1106 });
1107 }
1108 Ok(self)
1109 }
1110
1111 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1112 let query = {
1113 let grammar = self
1114 .grammar
1115 .as_ref()
1116 .ok_or_else(|| anyhow!("no grammar for language"))?;
1117 Query::new(&grammar.ts_language, source)?
1118 };
1119
1120 let mut override_configs_by_id = HashMap::default();
1121 for (ix, name) in query.capture_names().iter().enumerate() {
1122 if !name.starts_with('_') {
1123 let value = self.config.overrides.remove(*name).unwrap_or_default();
1124 for server_name in &value.opt_into_language_servers {
1125 if !self
1126 .config
1127 .scope_opt_in_language_servers
1128 .contains(server_name)
1129 {
1130 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1131 }
1132 }
1133
1134 override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1135 }
1136 }
1137
1138 if !self.config.overrides.is_empty() {
1139 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1140 Err(anyhow!(
1141 "language {:?} has overrides in config not in query: {keys:?}",
1142 self.config.name
1143 ))?;
1144 }
1145
1146 for disabled_scope_name in self
1147 .config
1148 .brackets
1149 .disabled_scopes_by_bracket_ix
1150 .iter()
1151 .flatten()
1152 {
1153 if !override_configs_by_id
1154 .values()
1155 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1156 {
1157 Err(anyhow!(
1158 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1159 self.config.name
1160 ))?;
1161 }
1162 }
1163
1164 for (name, override_config) in override_configs_by_id.values_mut() {
1165 override_config.disabled_bracket_ixs = self
1166 .config
1167 .brackets
1168 .disabled_scopes_by_bracket_ix
1169 .iter()
1170 .enumerate()
1171 .filter_map(|(ix, disabled_scope_names)| {
1172 if disabled_scope_names.contains(name) {
1173 Some(ix as u16)
1174 } else {
1175 None
1176 }
1177 })
1178 .collect();
1179 }
1180
1181 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1182
1183 let grammar = self
1184 .grammar_mut()
1185 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1186 grammar.override_config = Some(OverrideConfig {
1187 query,
1188 values: override_configs_by_id,
1189 });
1190 Ok(self)
1191 }
1192
1193 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1194 let grammar = self
1195 .grammar_mut()
1196 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1197
1198 let query = Query::new(&grammar.ts_language, source)?;
1199 let mut redaction_capture_ix = None;
1200 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1201
1202 if let Some(redaction_capture_ix) = redaction_capture_ix {
1203 grammar.redactions_config = Some(RedactionConfig {
1204 query,
1205 redaction_capture_ix,
1206 });
1207 }
1208
1209 Ok(self)
1210 }
1211
1212 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1213 Arc::get_mut(self.grammar.as_mut()?)
1214 }
1215
1216 pub fn name(&self) -> Arc<str> {
1217 self.config.name.clone()
1218 }
1219
1220 pub fn code_fence_block_name(&self) -> Arc<str> {
1221 self.config
1222 .code_fence_block_name
1223 .clone()
1224 .unwrap_or_else(|| self.config.name.to_lowercase().into())
1225 }
1226
1227 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1228 self.context_provider.clone()
1229 }
1230
1231 pub fn highlight_text<'a>(
1232 self: &'a Arc<Self>,
1233 text: &'a Rope,
1234 range: Range<usize>,
1235 ) -> Vec<(Range<usize>, HighlightId)> {
1236 let mut result = Vec::new();
1237 if let Some(grammar) = &self.grammar {
1238 let tree = grammar.parse_text(text, None);
1239 let captures =
1240 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1241 grammar.highlights_query.as_ref()
1242 });
1243 let highlight_maps = vec![grammar.highlight_map()];
1244 let mut offset = 0;
1245 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1246 let end_offset = offset + chunk.text.len();
1247 if let Some(highlight_id) = chunk.syntax_highlight_id {
1248 if !highlight_id.is_default() {
1249 result.push((offset..end_offset, highlight_id));
1250 }
1251 }
1252 offset = end_offset;
1253 }
1254 }
1255 result
1256 }
1257
1258 pub fn path_suffixes(&self) -> &[String] {
1259 &self.config.matcher.path_suffixes
1260 }
1261
1262 pub fn should_autoclose_before(&self, c: char) -> bool {
1263 c.is_whitespace() || self.config.autoclose_before.contains(c)
1264 }
1265
1266 pub fn set_theme(&self, theme: &SyntaxTheme) {
1267 if let Some(grammar) = self.grammar.as_ref() {
1268 if let Some(highlights_query) = &grammar.highlights_query {
1269 *grammar.highlight_map.lock() =
1270 HighlightMap::new(highlights_query.capture_names(), theme);
1271 }
1272 }
1273 }
1274
1275 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1276 self.grammar.as_ref()
1277 }
1278
1279 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1280 LanguageScope {
1281 language: self.clone(),
1282 override_id: None,
1283 }
1284 }
1285
1286 pub fn prettier_parser_name(&self) -> Option<&str> {
1287 self.config.prettier_parser_name.as_deref()
1288 }
1289
1290 pub fn prettier_plugins(&self) -> &Vec<Arc<str>> {
1291 &self.config.prettier_plugins
1292 }
1293}
1294
1295impl LanguageScope {
1296 pub fn collapsed_placeholder(&self) -> &str {
1297 self.language.config.collapsed_placeholder.as_ref()
1298 }
1299
1300 /// Returns line prefix that is inserted in e.g. line continuations or
1301 /// in `toggle comments` action.
1302 pub fn line_comment_prefixes(&self) -> Option<&Vec<Arc<str>>> {
1303 Override::as_option(
1304 self.config_override().map(|o| &o.line_comments),
1305 Some(&self.language.config.line_comments),
1306 )
1307 }
1308
1309 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1310 Override::as_option(
1311 self.config_override().map(|o| &o.block_comment),
1312 self.language.config.block_comment.as_ref(),
1313 )
1314 .map(|e| (&e.0, &e.1))
1315 }
1316
1317 /// Returns a list of language-specific word characters.
1318 ///
1319 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1320 /// the purpose of actions like 'move to next word end` or whole-word search.
1321 /// It additionally accounts for language's additional word characters.
1322 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1323 Override::as_option(
1324 self.config_override().map(|o| &o.word_characters),
1325 Some(&self.language.config.word_characters),
1326 )
1327 }
1328
1329 /// Returns a list of bracket pairs for a given language with an additional
1330 /// piece of information about whether the particular bracket pair is currently active for a given language.
1331 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1332 let mut disabled_ids = self
1333 .config_override()
1334 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1335 self.language
1336 .config
1337 .brackets
1338 .pairs
1339 .iter()
1340 .enumerate()
1341 .map(move |(ix, bracket)| {
1342 let mut is_enabled = true;
1343 if let Some(next_disabled_ix) = disabled_ids.first() {
1344 if ix == *next_disabled_ix as usize {
1345 disabled_ids = &disabled_ids[1..];
1346 is_enabled = false;
1347 }
1348 }
1349 (bracket, is_enabled)
1350 })
1351 }
1352
1353 pub fn should_autoclose_before(&self, c: char) -> bool {
1354 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1355 }
1356
1357 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1358 let config = &self.language.config;
1359 let opt_in_servers = &config.scope_opt_in_language_servers;
1360 if opt_in_servers.iter().any(|o| *o == *name.0) {
1361 if let Some(over) = self.config_override() {
1362 over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1363 } else {
1364 false
1365 }
1366 } else {
1367 true
1368 }
1369 }
1370
1371 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1372 let id = self.override_id?;
1373 let grammar = self.language.grammar.as_ref()?;
1374 let override_config = grammar.override_config.as_ref()?;
1375 override_config.values.get(&id).map(|e| &e.1)
1376 }
1377}
1378
1379impl Hash for Language {
1380 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1381 self.id.hash(state)
1382 }
1383}
1384
1385impl PartialEq for Language {
1386 fn eq(&self, other: &Self) -> bool {
1387 self.id.eq(&other.id)
1388 }
1389}
1390
1391impl Eq for Language {}
1392
1393impl Debug for Language {
1394 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1395 f.debug_struct("Language")
1396 .field("name", &self.config.name)
1397 .finish()
1398 }
1399}
1400
1401impl Grammar {
1402 pub fn id(&self) -> GrammarId {
1403 self.id
1404 }
1405
1406 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1407 PARSER.with(|parser| {
1408 let mut parser = parser.borrow_mut();
1409 parser
1410 .set_language(&self.ts_language)
1411 .expect("incompatible grammar");
1412 let mut chunks = text.chunks_in_range(0..text.len());
1413 parser
1414 .parse_with(
1415 &mut move |offset, _| {
1416 chunks.seek(offset);
1417 chunks.next().unwrap_or("").as_bytes()
1418 },
1419 old_tree.as_ref(),
1420 )
1421 .unwrap()
1422 })
1423 }
1424
1425 pub fn highlight_map(&self) -> HighlightMap {
1426 self.highlight_map.lock().clone()
1427 }
1428
1429 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1430 let capture_id = self
1431 .highlights_query
1432 .as_ref()?
1433 .capture_index_for_name(name)?;
1434 Some(self.highlight_map.lock().get(capture_id))
1435 }
1436}
1437
1438impl CodeLabel {
1439 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1440 let mut result = Self {
1441 runs: Vec::new(),
1442 filter_range: 0..text.len(),
1443 text,
1444 };
1445 if let Some(filter_text) = filter_text {
1446 if let Some(ix) = result.text.find(filter_text) {
1447 result.filter_range = ix..ix + filter_text.len();
1448 }
1449 }
1450 result
1451 }
1452}
1453
1454impl Ord for LanguageMatcher {
1455 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1456 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1457 self.first_line_pattern
1458 .as_ref()
1459 .map(Regex::as_str)
1460 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1461 })
1462 }
1463}
1464
1465impl PartialOrd for LanguageMatcher {
1466 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1467 Some(self.cmp(other))
1468 }
1469}
1470
1471impl Eq for LanguageMatcher {}
1472
1473impl PartialEq for LanguageMatcher {
1474 fn eq(&self, other: &Self) -> bool {
1475 self.path_suffixes == other.path_suffixes
1476 && self.first_line_pattern.as_ref().map(Regex::as_str)
1477 == other.first_line_pattern.as_ref().map(Regex::as_str)
1478 }
1479}
1480
1481#[cfg(any(test, feature = "test-support"))]
1482impl Default for FakeLspAdapter {
1483 fn default() -> Self {
1484 Self {
1485 name: "the-fake-language-server",
1486 capabilities: lsp::LanguageServer::full_capabilities(),
1487 initializer: None,
1488 disk_based_diagnostics_progress_token: None,
1489 initialization_options: None,
1490 disk_based_diagnostics_sources: Vec::new(),
1491 prettier_plugins: Vec::new(),
1492 language_server_binary: LanguageServerBinary {
1493 path: "/the/fake/lsp/path".into(),
1494 arguments: vec![],
1495 env: Default::default(),
1496 },
1497 }
1498 }
1499}
1500
1501#[cfg(any(test, feature = "test-support"))]
1502#[async_trait(?Send)]
1503impl LspAdapter for FakeLspAdapter {
1504 fn name(&self) -> LanguageServerName {
1505 LanguageServerName(self.name.into())
1506 }
1507
1508 fn get_language_server_command<'a>(
1509 self: Arc<Self>,
1510 _: Arc<Language>,
1511 _: Arc<Path>,
1512 _: Arc<dyn LspAdapterDelegate>,
1513 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1514 _: &'a mut AsyncAppContext,
1515 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1516 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1517 }
1518
1519 async fn fetch_latest_server_version(
1520 &self,
1521 _: &dyn LspAdapterDelegate,
1522 ) -> Result<Box<dyn 'static + Send + Any>> {
1523 unreachable!();
1524 }
1525
1526 async fn fetch_server_binary(
1527 &self,
1528 _: Box<dyn 'static + Send + Any>,
1529 _: PathBuf,
1530 _: &dyn LspAdapterDelegate,
1531 ) -> Result<LanguageServerBinary> {
1532 unreachable!();
1533 }
1534
1535 async fn cached_server_binary(
1536 &self,
1537 _: PathBuf,
1538 _: &dyn LspAdapterDelegate,
1539 ) -> Option<LanguageServerBinary> {
1540 unreachable!();
1541 }
1542
1543 async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1544 unreachable!();
1545 }
1546
1547 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1548
1549 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1550 self.disk_based_diagnostics_sources.clone()
1551 }
1552
1553 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1554 self.disk_based_diagnostics_progress_token.clone()
1555 }
1556
1557 async fn initialization_options(
1558 self: Arc<Self>,
1559 _: &Arc<dyn LspAdapterDelegate>,
1560 ) -> Result<Option<Value>> {
1561 Ok(self.initialization_options.clone())
1562 }
1563
1564 fn as_fake(&self) -> Option<&FakeLspAdapter> {
1565 Some(self)
1566 }
1567}
1568
1569fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1570 for (ix, name) in query.capture_names().iter().enumerate() {
1571 for (capture_name, index) in captures.iter_mut() {
1572 if capture_name == name {
1573 **index = Some(ix as u32);
1574 break;
1575 }
1576 }
1577 }
1578}
1579
1580pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1581 lsp::Position::new(point.row, point.column)
1582}
1583
1584pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1585 Unclipped(PointUtf16::new(point.line, point.character))
1586}
1587
1588pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1589 lsp::Range {
1590 start: point_to_lsp(range.start),
1591 end: point_to_lsp(range.end),
1592 }
1593}
1594
1595pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1596 let mut start = point_from_lsp(range.start);
1597 let mut end = point_from_lsp(range.end);
1598 if start > end {
1599 mem::swap(&mut start, &mut end);
1600 }
1601 start..end
1602}
1603
1604#[cfg(test)]
1605mod tests {
1606 use super::*;
1607 use gpui::TestAppContext;
1608
1609 #[gpui::test(iterations = 10)]
1610 async fn test_language_loading(cx: &mut TestAppContext) {
1611 let languages = LanguageRegistry::test(cx.executor());
1612 let languages = Arc::new(languages);
1613 languages.register_native_grammars([
1614 ("json", tree_sitter_json::language()),
1615 ("rust", tree_sitter_rust::language()),
1616 ]);
1617 languages.register_test_language(LanguageConfig {
1618 name: "JSON".into(),
1619 grammar: Some("json".into()),
1620 matcher: LanguageMatcher {
1621 path_suffixes: vec!["json".into()],
1622 ..Default::default()
1623 },
1624 ..Default::default()
1625 });
1626 languages.register_test_language(LanguageConfig {
1627 name: "Rust".into(),
1628 grammar: Some("rust".into()),
1629 matcher: LanguageMatcher {
1630 path_suffixes: vec!["rs".into()],
1631 ..Default::default()
1632 },
1633 ..Default::default()
1634 });
1635 assert_eq!(
1636 languages.language_names(),
1637 &[
1638 "JSON".to_string(),
1639 "Plain Text".to_string(),
1640 "Rust".to_string(),
1641 ]
1642 );
1643
1644 let rust1 = languages.language_for_name("Rust");
1645 let rust2 = languages.language_for_name("Rust");
1646
1647 // Ensure language is still listed even if it's being loaded.
1648 assert_eq!(
1649 languages.language_names(),
1650 &[
1651 "JSON".to_string(),
1652 "Plain Text".to_string(),
1653 "Rust".to_string(),
1654 ]
1655 );
1656
1657 let (rust1, rust2) = futures::join!(rust1, rust2);
1658 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1659
1660 // Ensure language is still listed even after loading it.
1661 assert_eq!(
1662 languages.language_names(),
1663 &[
1664 "JSON".to_string(),
1665 "Plain Text".to_string(),
1666 "Rust".to_string(),
1667 ]
1668 );
1669
1670 // Loading an unknown language returns an error.
1671 assert!(languages.language_for_name("Unknown").await.is_err());
1672 }
1673}