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