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