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