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