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