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