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