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