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::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: "".into(),
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}
871
872#[derive(Debug)]
873pub struct EmbeddingConfig {
874 pub query: Query,
875 pub item_capture_ix: u32,
876 pub name_capture_ix: Option<u32>,
877 pub context_capture_ix: Option<u32>,
878 pub collapse_capture_ix: Option<u32>,
879 pub keep_capture_ix: Option<u32>,
880}
881
882struct InjectionConfig {
883 query: Query,
884 content_capture_ix: u32,
885 language_capture_ix: Option<u32>,
886 patterns: Vec<InjectionPatternConfig>,
887}
888
889struct RedactionConfig {
890 pub query: Query,
891 pub redaction_capture_ix: u32,
892}
893
894#[derive(Clone, Debug, PartialEq)]
895enum RunnableCapture {
896 Named(SharedString),
897 Run,
898}
899
900struct RunnableConfig {
901 pub query: Query,
902 /// A mapping from capture indice to capture kind
903 pub extra_captures: Vec<RunnableCapture>,
904}
905
906struct OverrideConfig {
907 query: Query,
908 values: HashMap<u32, (String, LanguageConfigOverride)>,
909}
910
911#[derive(Default, Clone)]
912struct InjectionPatternConfig {
913 language: Option<Box<str>>,
914 combined: bool,
915}
916
917struct BracketConfig {
918 query: Query,
919 open_capture_ix: u32,
920 close_capture_ix: u32,
921}
922
923impl Language {
924 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
925 Self::new_with_id(LanguageId::new(), config, ts_language)
926 }
927
928 fn new_with_id(
929 id: LanguageId,
930 config: LanguageConfig,
931 ts_language: Option<tree_sitter::Language>,
932 ) -> Self {
933 Self {
934 id,
935 config,
936 grammar: ts_language.map(|ts_language| {
937 Arc::new(Grammar {
938 id: GrammarId::new(),
939 highlights_query: None,
940 brackets_config: None,
941 outline_config: None,
942 embedding_config: None,
943 indents_config: None,
944 injection_config: None,
945 override_config: None,
946 redactions_config: None,
947 runnable_config: None,
948 error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
949 ts_language,
950 highlight_map: Default::default(),
951 })
952 }),
953 context_provider: None,
954 }
955 }
956
957 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
958 self.context_provider = provider;
959 self
960 }
961
962 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
963 if let Some(query) = queries.highlights {
964 self = self
965 .with_highlights_query(query.as_ref())
966 .context("Error loading highlights query")?;
967 }
968 if let Some(query) = queries.brackets {
969 self = self
970 .with_brackets_query(query.as_ref())
971 .context("Error loading brackets query")?;
972 }
973 if let Some(query) = queries.indents {
974 self = self
975 .with_indents_query(query.as_ref())
976 .context("Error loading indents query")?;
977 }
978 if let Some(query) = queries.outline {
979 self = self
980 .with_outline_query(query.as_ref())
981 .context("Error loading outline query")?;
982 }
983 if let Some(query) = queries.embedding {
984 self = self
985 .with_embedding_query(query.as_ref())
986 .context("Error loading embedding query")?;
987 }
988 if let Some(query) = queries.injections {
989 self = self
990 .with_injection_query(query.as_ref())
991 .context("Error loading injection query")?;
992 }
993 if let Some(query) = queries.overrides {
994 self = self
995 .with_override_query(query.as_ref())
996 .context("Error loading override query")?;
997 }
998 if let Some(query) = queries.redactions {
999 self = self
1000 .with_redaction_query(query.as_ref())
1001 .context("Error loading redaction query")?;
1002 }
1003 if let Some(query) = queries.runnables {
1004 self = self
1005 .with_runnable_query(query.as_ref())
1006 .context("Error loading tests query")?;
1007 }
1008 Ok(self)
1009 }
1010
1011 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1012 let grammar = self
1013 .grammar_mut()
1014 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1015 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1016 Ok(self)
1017 }
1018
1019 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1020 let grammar = self
1021 .grammar_mut()
1022 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1023
1024 let query = Query::new(&grammar.ts_language, source)?;
1025 let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1026
1027 for name in query.capture_names().iter() {
1028 let kind = if *name == "run" {
1029 RunnableCapture::Run
1030 } else {
1031 RunnableCapture::Named(name.to_string().into())
1032 };
1033 extra_captures.push(kind);
1034 }
1035
1036 grammar.runnable_config = Some(RunnableConfig {
1037 extra_captures,
1038 query,
1039 });
1040
1041 Ok(self)
1042 }
1043
1044 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1045 let grammar = self
1046 .grammar_mut()
1047 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1048 let query = Query::new(&grammar.ts_language, source)?;
1049 let mut item_capture_ix = None;
1050 let mut name_capture_ix = None;
1051 let mut context_capture_ix = None;
1052 let mut extra_context_capture_ix = None;
1053 get_capture_indices(
1054 &query,
1055 &mut [
1056 ("item", &mut item_capture_ix),
1057 ("name", &mut name_capture_ix),
1058 ("context", &mut context_capture_ix),
1059 ("context.extra", &mut extra_context_capture_ix),
1060 ],
1061 );
1062 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1063 grammar.outline_config = Some(OutlineConfig {
1064 query,
1065 item_capture_ix,
1066 name_capture_ix,
1067 context_capture_ix,
1068 extra_context_capture_ix,
1069 });
1070 }
1071 Ok(self)
1072 }
1073
1074 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1075 let grammar = self
1076 .grammar_mut()
1077 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1078 let query = Query::new(&grammar.ts_language, source)?;
1079 let mut item_capture_ix = None;
1080 let mut name_capture_ix = None;
1081 let mut context_capture_ix = None;
1082 let mut collapse_capture_ix = None;
1083 let mut keep_capture_ix = None;
1084 get_capture_indices(
1085 &query,
1086 &mut [
1087 ("item", &mut item_capture_ix),
1088 ("name", &mut name_capture_ix),
1089 ("context", &mut context_capture_ix),
1090 ("keep", &mut keep_capture_ix),
1091 ("collapse", &mut collapse_capture_ix),
1092 ],
1093 );
1094 if let Some(item_capture_ix) = item_capture_ix {
1095 grammar.embedding_config = Some(EmbeddingConfig {
1096 query,
1097 item_capture_ix,
1098 name_capture_ix,
1099 context_capture_ix,
1100 collapse_capture_ix,
1101 keep_capture_ix,
1102 });
1103 }
1104 Ok(self)
1105 }
1106
1107 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1108 let grammar = self
1109 .grammar_mut()
1110 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1111 let query = Query::new(&grammar.ts_language, source)?;
1112 let mut open_capture_ix = None;
1113 let mut close_capture_ix = None;
1114 get_capture_indices(
1115 &query,
1116 &mut [
1117 ("open", &mut open_capture_ix),
1118 ("close", &mut close_capture_ix),
1119 ],
1120 );
1121 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1122 grammar.brackets_config = Some(BracketConfig {
1123 query,
1124 open_capture_ix,
1125 close_capture_ix,
1126 });
1127 }
1128 Ok(self)
1129 }
1130
1131 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1132 let grammar = self
1133 .grammar_mut()
1134 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1135 let query = Query::new(&grammar.ts_language, source)?;
1136 let mut indent_capture_ix = None;
1137 let mut start_capture_ix = None;
1138 let mut end_capture_ix = None;
1139 let mut outdent_capture_ix = None;
1140 get_capture_indices(
1141 &query,
1142 &mut [
1143 ("indent", &mut indent_capture_ix),
1144 ("start", &mut start_capture_ix),
1145 ("end", &mut end_capture_ix),
1146 ("outdent", &mut outdent_capture_ix),
1147 ],
1148 );
1149 if let Some(indent_capture_ix) = indent_capture_ix {
1150 grammar.indents_config = Some(IndentConfig {
1151 query,
1152 indent_capture_ix,
1153 start_capture_ix,
1154 end_capture_ix,
1155 outdent_capture_ix,
1156 });
1157 }
1158 Ok(self)
1159 }
1160
1161 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1162 let grammar = self
1163 .grammar_mut()
1164 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1165 let query = Query::new(&grammar.ts_language, source)?;
1166 let mut language_capture_ix = None;
1167 let mut content_capture_ix = None;
1168 get_capture_indices(
1169 &query,
1170 &mut [
1171 ("language", &mut language_capture_ix),
1172 ("content", &mut content_capture_ix),
1173 ],
1174 );
1175 let patterns = (0..query.pattern_count())
1176 .map(|ix| {
1177 let mut config = InjectionPatternConfig::default();
1178 for setting in query.property_settings(ix) {
1179 match setting.key.as_ref() {
1180 "language" => {
1181 config.language.clone_from(&setting.value);
1182 }
1183 "combined" => {
1184 config.combined = true;
1185 }
1186 _ => {}
1187 }
1188 }
1189 config
1190 })
1191 .collect();
1192 if let Some(content_capture_ix) = content_capture_ix {
1193 grammar.injection_config = Some(InjectionConfig {
1194 query,
1195 language_capture_ix,
1196 content_capture_ix,
1197 patterns,
1198 });
1199 }
1200 Ok(self)
1201 }
1202
1203 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1204 let query = {
1205 let grammar = self
1206 .grammar
1207 .as_ref()
1208 .ok_or_else(|| anyhow!("no grammar for language"))?;
1209 Query::new(&grammar.ts_language, source)?
1210 };
1211
1212 let mut override_configs_by_id = HashMap::default();
1213 for (ix, name) in query.capture_names().iter().enumerate() {
1214 if !name.starts_with('_') {
1215 let value = self.config.overrides.remove(*name).unwrap_or_default();
1216 for server_name in &value.opt_into_language_servers {
1217 if !self
1218 .config
1219 .scope_opt_in_language_servers
1220 .contains(server_name)
1221 {
1222 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1223 }
1224 }
1225
1226 override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1227 }
1228 }
1229
1230 if !self.config.overrides.is_empty() {
1231 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1232 Err(anyhow!(
1233 "language {:?} has overrides in config not in query: {keys:?}",
1234 self.config.name
1235 ))?;
1236 }
1237
1238 for disabled_scope_name in self
1239 .config
1240 .brackets
1241 .disabled_scopes_by_bracket_ix
1242 .iter()
1243 .flatten()
1244 {
1245 if !override_configs_by_id
1246 .values()
1247 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1248 {
1249 Err(anyhow!(
1250 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1251 self.config.name
1252 ))?;
1253 }
1254 }
1255
1256 for (name, override_config) in override_configs_by_id.values_mut() {
1257 override_config.disabled_bracket_ixs = self
1258 .config
1259 .brackets
1260 .disabled_scopes_by_bracket_ix
1261 .iter()
1262 .enumerate()
1263 .filter_map(|(ix, disabled_scope_names)| {
1264 if disabled_scope_names.contains(name) {
1265 Some(ix as u16)
1266 } else {
1267 None
1268 }
1269 })
1270 .collect();
1271 }
1272
1273 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1274
1275 let grammar = self
1276 .grammar_mut()
1277 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1278 grammar.override_config = Some(OverrideConfig {
1279 query,
1280 values: override_configs_by_id,
1281 });
1282 Ok(self)
1283 }
1284
1285 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1286 let grammar = self
1287 .grammar_mut()
1288 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1289
1290 let query = Query::new(&grammar.ts_language, source)?;
1291 let mut redaction_capture_ix = None;
1292 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1293
1294 if let Some(redaction_capture_ix) = redaction_capture_ix {
1295 grammar.redactions_config = Some(RedactionConfig {
1296 query,
1297 redaction_capture_ix,
1298 });
1299 }
1300
1301 Ok(self)
1302 }
1303
1304 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1305 Arc::get_mut(self.grammar.as_mut()?)
1306 }
1307
1308 pub fn name(&self) -> Arc<str> {
1309 self.config.name.clone()
1310 }
1311
1312 pub fn code_fence_block_name(&self) -> Arc<str> {
1313 self.config
1314 .code_fence_block_name
1315 .clone()
1316 .unwrap_or_else(|| self.config.name.to_lowercase().into())
1317 }
1318
1319 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1320 self.context_provider.clone()
1321 }
1322
1323 pub fn highlight_text<'a>(
1324 self: &'a Arc<Self>,
1325 text: &'a Rope,
1326 range: Range<usize>,
1327 ) -> Vec<(Range<usize>, HighlightId)> {
1328 let mut result = Vec::new();
1329 if let Some(grammar) = &self.grammar {
1330 let tree = grammar.parse_text(text, None);
1331 let captures =
1332 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1333 grammar.highlights_query.as_ref()
1334 });
1335 let highlight_maps = vec![grammar.highlight_map()];
1336 let mut offset = 0;
1337 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1338 let end_offset = offset + chunk.text.len();
1339 if let Some(highlight_id) = chunk.syntax_highlight_id {
1340 if !highlight_id.is_default() {
1341 result.push((offset..end_offset, highlight_id));
1342 }
1343 }
1344 offset = end_offset;
1345 }
1346 }
1347 result
1348 }
1349
1350 pub fn path_suffixes(&self) -> &[String] {
1351 &self.config.matcher.path_suffixes
1352 }
1353
1354 pub fn should_autoclose_before(&self, c: char) -> bool {
1355 c.is_whitespace() || self.config.autoclose_before.contains(c)
1356 }
1357
1358 pub fn set_theme(&self, theme: &SyntaxTheme) {
1359 if let Some(grammar) = self.grammar.as_ref() {
1360 if let Some(highlights_query) = &grammar.highlights_query {
1361 *grammar.highlight_map.lock() =
1362 HighlightMap::new(highlights_query.capture_names(), theme);
1363 }
1364 }
1365 }
1366
1367 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1368 self.grammar.as_ref()
1369 }
1370
1371 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1372 LanguageScope {
1373 language: self.clone(),
1374 override_id: None,
1375 }
1376 }
1377
1378 pub fn lsp_id(&self) -> String {
1379 match self.config.name.as_ref() {
1380 "Plain Text" => "plaintext".to_string(),
1381 language_name => language_name.to_lowercase(),
1382 }
1383 }
1384
1385 pub fn prettier_parser_name(&self) -> Option<&str> {
1386 self.config.prettier_parser_name.as_deref()
1387 }
1388}
1389
1390impl LanguageScope {
1391 pub fn collapsed_placeholder(&self) -> &str {
1392 self.language.config.collapsed_placeholder.as_ref()
1393 }
1394
1395 /// Returns line prefix that is inserted in e.g. line continuations or
1396 /// in `toggle comments` action.
1397 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1398 Override::as_option(
1399 self.config_override().map(|o| &o.line_comments),
1400 Some(&self.language.config.line_comments),
1401 )
1402 .map_or(&[] as &[_], |e| e.as_slice())
1403 }
1404
1405 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1406 Override::as_option(
1407 self.config_override().map(|o| &o.block_comment),
1408 self.language.config.block_comment.as_ref(),
1409 )
1410 .map(|e| (&e.0, &e.1))
1411 }
1412
1413 /// Returns a list of language-specific word characters.
1414 ///
1415 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1416 /// the purpose of actions like 'move to next word end` or whole-word search.
1417 /// It additionally accounts for language's additional word characters.
1418 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1419 Override::as_option(
1420 self.config_override().map(|o| &o.word_characters),
1421 Some(&self.language.config.word_characters),
1422 )
1423 }
1424
1425 /// Returns a list of bracket pairs for a given language with an additional
1426 /// piece of information about whether the particular bracket pair is currently active for a given language.
1427 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1428 let mut disabled_ids = self
1429 .config_override()
1430 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1431 self.language
1432 .config
1433 .brackets
1434 .pairs
1435 .iter()
1436 .enumerate()
1437 .map(move |(ix, bracket)| {
1438 let mut is_enabled = true;
1439 if let Some(next_disabled_ix) = disabled_ids.first() {
1440 if ix == *next_disabled_ix as usize {
1441 disabled_ids = &disabled_ids[1..];
1442 is_enabled = false;
1443 }
1444 }
1445 (bracket, is_enabled)
1446 })
1447 }
1448
1449 pub fn should_autoclose_before(&self, c: char) -> bool {
1450 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1451 }
1452
1453 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1454 let config = &self.language.config;
1455 let opt_in_servers = &config.scope_opt_in_language_servers;
1456 if opt_in_servers.iter().any(|o| *o == *name.0) {
1457 if let Some(over) = self.config_override() {
1458 over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1459 } else {
1460 false
1461 }
1462 } else {
1463 true
1464 }
1465 }
1466
1467 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1468 let id = self.override_id?;
1469 let grammar = self.language.grammar.as_ref()?;
1470 let override_config = grammar.override_config.as_ref()?;
1471 override_config.values.get(&id).map(|e| &e.1)
1472 }
1473}
1474
1475impl Hash for Language {
1476 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1477 self.id.hash(state)
1478 }
1479}
1480
1481impl PartialEq for Language {
1482 fn eq(&self, other: &Self) -> bool {
1483 self.id.eq(&other.id)
1484 }
1485}
1486
1487impl Eq for Language {}
1488
1489impl Debug for Language {
1490 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1491 f.debug_struct("Language")
1492 .field("name", &self.config.name)
1493 .finish()
1494 }
1495}
1496
1497impl Grammar {
1498 pub fn id(&self) -> GrammarId {
1499 self.id
1500 }
1501
1502 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1503 with_parser(|parser| {
1504 parser
1505 .set_language(&self.ts_language)
1506 .expect("incompatible grammar");
1507 let mut chunks = text.chunks_in_range(0..text.len());
1508 parser
1509 .parse_with(
1510 &mut move |offset, _| {
1511 chunks.seek(offset);
1512 chunks.next().unwrap_or("").as_bytes()
1513 },
1514 old_tree.as_ref(),
1515 )
1516 .unwrap()
1517 })
1518 }
1519
1520 pub fn highlight_map(&self) -> HighlightMap {
1521 self.highlight_map.lock().clone()
1522 }
1523
1524 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1525 let capture_id = self
1526 .highlights_query
1527 .as_ref()?
1528 .capture_index_for_name(name)?;
1529 Some(self.highlight_map.lock().get(capture_id))
1530 }
1531}
1532
1533impl CodeLabel {
1534 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1535 let mut result = Self {
1536 runs: Vec::new(),
1537 filter_range: 0..text.len(),
1538 text,
1539 };
1540 if let Some(filter_text) = filter_text {
1541 if let Some(ix) = result.text.find(filter_text) {
1542 result.filter_range = ix..ix + filter_text.len();
1543 }
1544 }
1545 result
1546 }
1547
1548 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1549 let start_ix = self.text.len();
1550 self.text.push_str(text);
1551 let end_ix = self.text.len();
1552 if let Some(highlight) = highlight {
1553 self.runs.push((start_ix..end_ix, highlight));
1554 }
1555 }
1556}
1557
1558impl Ord for LanguageMatcher {
1559 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1560 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1561 self.first_line_pattern
1562 .as_ref()
1563 .map(Regex::as_str)
1564 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1565 })
1566 }
1567}
1568
1569impl PartialOrd for LanguageMatcher {
1570 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1571 Some(self.cmp(other))
1572 }
1573}
1574
1575impl Eq for LanguageMatcher {}
1576
1577impl PartialEq for LanguageMatcher {
1578 fn eq(&self, other: &Self) -> bool {
1579 self.path_suffixes == other.path_suffixes
1580 && self.first_line_pattern.as_ref().map(Regex::as_str)
1581 == other.first_line_pattern.as_ref().map(Regex::as_str)
1582 }
1583}
1584
1585#[cfg(any(test, feature = "test-support"))]
1586impl Default for FakeLspAdapter {
1587 fn default() -> Self {
1588 Self {
1589 name: "the-fake-language-server",
1590 capabilities: lsp::LanguageServer::full_capabilities(),
1591 initializer: None,
1592 disk_based_diagnostics_progress_token: None,
1593 initialization_options: None,
1594 disk_based_diagnostics_sources: Vec::new(),
1595 prettier_plugins: Vec::new(),
1596 language_server_binary: LanguageServerBinary {
1597 path: "/the/fake/lsp/path".into(),
1598 arguments: vec![],
1599 env: Default::default(),
1600 },
1601 }
1602 }
1603}
1604
1605#[cfg(any(test, feature = "test-support"))]
1606#[async_trait(?Send)]
1607impl LspAdapter for FakeLspAdapter {
1608 fn name(&self) -> LanguageServerName {
1609 LanguageServerName(self.name.into())
1610 }
1611
1612 fn get_language_server_command<'a>(
1613 self: Arc<Self>,
1614 _: Arc<Language>,
1615 _: Arc<Path>,
1616 _: Arc<dyn LspAdapterDelegate>,
1617 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1618 _: &'a mut AsyncAppContext,
1619 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1620 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1621 }
1622
1623 async fn fetch_latest_server_version(
1624 &self,
1625 _: &dyn LspAdapterDelegate,
1626 ) -> Result<Box<dyn 'static + Send + Any>> {
1627 unreachable!();
1628 }
1629
1630 async fn fetch_server_binary(
1631 &self,
1632 _: Box<dyn 'static + Send + Any>,
1633 _: PathBuf,
1634 _: &dyn LspAdapterDelegate,
1635 ) -> Result<LanguageServerBinary> {
1636 unreachable!();
1637 }
1638
1639 async fn cached_server_binary(
1640 &self,
1641 _: PathBuf,
1642 _: &dyn LspAdapterDelegate,
1643 ) -> Option<LanguageServerBinary> {
1644 unreachable!();
1645 }
1646
1647 async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1648 unreachable!();
1649 }
1650
1651 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1652
1653 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1654 self.disk_based_diagnostics_sources.clone()
1655 }
1656
1657 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1658 self.disk_based_diagnostics_progress_token.clone()
1659 }
1660
1661 async fn initialization_options(
1662 self: Arc<Self>,
1663 _: &Arc<dyn LspAdapterDelegate>,
1664 ) -> Result<Option<Value>> {
1665 Ok(self.initialization_options.clone())
1666 }
1667
1668 fn as_fake(&self) -> Option<&FakeLspAdapter> {
1669 Some(self)
1670 }
1671}
1672
1673fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1674 for (ix, name) in query.capture_names().iter().enumerate() {
1675 for (capture_name, index) in captures.iter_mut() {
1676 if capture_name == name {
1677 **index = Some(ix as u32);
1678 break;
1679 }
1680 }
1681 }
1682}
1683
1684pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1685 lsp::Position::new(point.row, point.column)
1686}
1687
1688pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1689 Unclipped(PointUtf16::new(point.line, point.character))
1690}
1691
1692pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1693 lsp::Range {
1694 start: point_to_lsp(range.start),
1695 end: point_to_lsp(range.end),
1696 }
1697}
1698
1699pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1700 let mut start = point_from_lsp(range.start);
1701 let mut end = point_from_lsp(range.end);
1702 if start > end {
1703 mem::swap(&mut start, &mut end);
1704 }
1705 start..end
1706}
1707
1708#[cfg(test)]
1709mod tests {
1710 use super::*;
1711 use gpui::TestAppContext;
1712
1713 #[gpui::test(iterations = 10)]
1714 async fn test_language_loading(cx: &mut TestAppContext) {
1715 let languages = LanguageRegistry::test(cx.executor());
1716 let languages = Arc::new(languages);
1717 languages.register_native_grammars([
1718 ("json", tree_sitter_json::language()),
1719 ("rust", tree_sitter_rust::language()),
1720 ]);
1721 languages.register_test_language(LanguageConfig {
1722 name: "JSON".into(),
1723 grammar: Some("json".into()),
1724 matcher: LanguageMatcher {
1725 path_suffixes: vec!["json".into()],
1726 ..Default::default()
1727 },
1728 ..Default::default()
1729 });
1730 languages.register_test_language(LanguageConfig {
1731 name: "Rust".into(),
1732 grammar: Some("rust".into()),
1733 matcher: LanguageMatcher {
1734 path_suffixes: vec!["rs".into()],
1735 ..Default::default()
1736 },
1737 ..Default::default()
1738 });
1739 assert_eq!(
1740 languages.language_names(),
1741 &[
1742 "JSON".to_string(),
1743 "Plain Text".to_string(),
1744 "Rust".to_string(),
1745 ]
1746 );
1747
1748 let rust1 = languages.language_for_name("Rust");
1749 let rust2 = languages.language_for_name("Rust");
1750
1751 // Ensure language is still listed even if it's being loaded.
1752 assert_eq!(
1753 languages.language_names(),
1754 &[
1755 "JSON".to_string(),
1756 "Plain Text".to_string(),
1757 "Rust".to_string(),
1758 ]
1759 );
1760
1761 let (rust1, rust2) = futures::join!(rust1, rust2);
1762 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1763
1764 // Ensure language is still listed even after loading it.
1765 assert_eq!(
1766 languages.language_names(),
1767 &[
1768 "JSON".to_string(),
1769 "Plain Text".to_string(),
1770 "Rust".to_string(),
1771 ]
1772 );
1773
1774 // Loading an unknown language returns an error.
1775 assert!(languages.language_for_name("Unknown").await.is_err());
1776 }
1777}