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