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