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