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