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