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