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)]
20pub mod 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 settings::WorktreeId;
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, LazyLock,
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
114static NEXT_LANGUAGE_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
115static NEXT_GRAMMAR_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
116static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
117 wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
118});
119
120/// A shared grammar for plain text, exposed for reuse by downstream crates.
121pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
122 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) -> WorktreeId;
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.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.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 /// If true, this language is only for syntax highlighting via an injection into other
632 /// languages, but should not appear to the user as a distinct language.
633 #[serde(default)]
634 pub hidden: bool,
635}
636
637#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
638pub struct LanguageMatcher {
639 /// 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`.
640 #[serde(default)]
641 pub path_suffixes: Vec<String>,
642 /// A regex pattern that determines whether the language should be assigned to a file or not.
643 #[serde(
644 default,
645 serialize_with = "serialize_regex",
646 deserialize_with = "deserialize_regex"
647 )]
648 #[schemars(schema_with = "regex_json_schema")]
649 pub first_line_pattern: Option<Regex>,
650}
651
652/// Represents a language for the given range. Some languages (e.g. HTML)
653/// interleave several languages together, thus a single buffer might actually contain
654/// several nested scopes.
655#[derive(Clone, Debug)]
656pub struct LanguageScope {
657 language: Arc<Language>,
658 override_id: Option<u32>,
659}
660
661#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
662pub struct LanguageConfigOverride {
663 #[serde(default)]
664 pub line_comments: Override<Vec<Arc<str>>>,
665 #[serde(default)]
666 pub block_comment: Override<(Arc<str>, Arc<str>)>,
667 #[serde(skip_deserializing)]
668 #[schemars(skip)]
669 pub disabled_bracket_ixs: Vec<u16>,
670 #[serde(default)]
671 pub word_characters: Override<HashSet<char>>,
672 #[serde(default)]
673 pub opt_into_language_servers: Vec<String>,
674}
675
676#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
677#[serde(untagged)]
678pub enum Override<T> {
679 Remove { remove: bool },
680 Set(T),
681}
682
683impl<T> Default for Override<T> {
684 fn default() -> Self {
685 Override::Remove { remove: false }
686 }
687}
688
689impl<T> Override<T> {
690 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
691 match this {
692 Some(Self::Set(value)) => Some(value),
693 Some(Self::Remove { remove: true }) => None,
694 Some(Self::Remove { remove: false }) | None => original,
695 }
696 }
697}
698
699impl Default for LanguageConfig {
700 fn default() -> Self {
701 Self {
702 name: Arc::default(),
703 code_fence_block_name: None,
704 grammar: None,
705 matcher: LanguageMatcher::default(),
706 brackets: Default::default(),
707 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
708 increase_indent_pattern: Default::default(),
709 decrease_indent_pattern: Default::default(),
710 autoclose_before: Default::default(),
711 line_comments: Default::default(),
712 block_comment: Default::default(),
713 scope_opt_in_language_servers: Default::default(),
714 overrides: Default::default(),
715 word_characters: Default::default(),
716 collapsed_placeholder: Default::default(),
717 hard_tabs: None,
718 tab_size: None,
719 soft_wrap: None,
720 prettier_parser_name: None,
721 hidden: false,
722 }
723 }
724}
725
726fn auto_indent_using_last_non_empty_line_default() -> bool {
727 true
728}
729
730fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
731 let source = Option::<String>::deserialize(d)?;
732 if let Some(source) = source {
733 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
734 } else {
735 Ok(None)
736 }
737}
738
739fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
740 Schema::Object(SchemaObject {
741 instance_type: Some(InstanceType::String.into()),
742 ..Default::default()
743 })
744}
745
746fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
747where
748 S: Serializer,
749{
750 match regex {
751 Some(regex) => serializer.serialize_str(regex.as_str()),
752 None => serializer.serialize_none(),
753 }
754}
755
756#[doc(hidden)]
757#[cfg(any(test, feature = "test-support"))]
758pub struct FakeLspAdapter {
759 pub name: &'static str,
760 pub initialization_options: Option<Value>,
761 pub capabilities: lsp::ServerCapabilities,
762 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
763 pub disk_based_diagnostics_progress_token: Option<String>,
764 pub disk_based_diagnostics_sources: Vec<String>,
765 pub prettier_plugins: Vec<&'static str>,
766 pub language_server_binary: LanguageServerBinary,
767}
768
769/// Configuration of handling bracket pairs for a given language.
770///
771/// This struct includes settings for defining which pairs of characters are considered brackets and
772/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
773#[derive(Clone, Debug, Default, JsonSchema)]
774pub struct BracketPairConfig {
775 /// A list of character pairs that should be treated as brackets in the context of a given language.
776 pub pairs: Vec<BracketPair>,
777 /// A list of tree-sitter scopes for which a given bracket should not be active.
778 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
779 #[schemars(skip)]
780 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
781}
782
783fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
784 Option::<Vec<BracketPairContent>>::json_schema(gen)
785}
786
787#[derive(Deserialize, JsonSchema)]
788pub struct BracketPairContent {
789 #[serde(flatten)]
790 pub bracket_pair: BracketPair,
791 #[serde(default)]
792 pub not_in: Vec<String>,
793}
794
795impl<'de> Deserialize<'de> for BracketPairConfig {
796 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
797 where
798 D: Deserializer<'de>,
799 {
800 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
801 let mut brackets = Vec::with_capacity(result.len());
802 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
803 for entry in result {
804 brackets.push(entry.bracket_pair);
805 disabled_scopes_by_bracket_ix.push(entry.not_in);
806 }
807
808 Ok(BracketPairConfig {
809 pairs: brackets,
810 disabled_scopes_by_bracket_ix,
811 })
812 }
813}
814
815/// Describes a single bracket pair and how an editor should react to e.g. inserting
816/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
817#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
818pub struct BracketPair {
819 /// Starting substring for a bracket.
820 pub start: String,
821 /// Ending substring for a bracket.
822 pub end: String,
823 /// True if `end` should be automatically inserted right after `start` characters.
824 pub close: bool,
825 /// True if selected text should be surrounded by `start` and `end` characters.
826 #[serde(default = "default_true")]
827 pub surround: bool,
828 /// True if an extra newline should be inserted while the cursor is in the middle
829 /// of that bracket pair.
830 pub newline: bool,
831}
832
833#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
834pub(crate) struct LanguageId(usize);
835
836impl LanguageId {
837 pub(crate) fn new() -> Self {
838 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
839 }
840}
841
842pub struct Language {
843 pub(crate) id: LanguageId,
844 pub(crate) config: LanguageConfig,
845 pub(crate) grammar: Option<Arc<Grammar>>,
846 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
847}
848
849#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
850pub struct GrammarId(pub usize);
851
852impl GrammarId {
853 pub(crate) fn new() -> Self {
854 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
855 }
856}
857
858pub struct Grammar {
859 id: GrammarId,
860 pub ts_language: tree_sitter::Language,
861 pub(crate) error_query: Query,
862 pub(crate) highlights_query: Option<Query>,
863 pub(crate) brackets_config: Option<BracketConfig>,
864 pub(crate) redactions_config: Option<RedactionConfig>,
865 pub(crate) runnable_config: Option<RunnableConfig>,
866 pub(crate) indents_config: Option<IndentConfig>,
867 pub outline_config: Option<OutlineConfig>,
868 pub embedding_config: Option<EmbeddingConfig>,
869 pub(crate) injection_config: Option<InjectionConfig>,
870 pub(crate) override_config: Option<OverrideConfig>,
871 pub(crate) highlight_map: Mutex<HighlightMap>,
872}
873
874struct IndentConfig {
875 query: Query,
876 indent_capture_ix: u32,
877 start_capture_ix: Option<u32>,
878 end_capture_ix: Option<u32>,
879 outdent_capture_ix: Option<u32>,
880}
881
882pub struct OutlineConfig {
883 pub query: Query,
884 pub item_capture_ix: u32,
885 pub name_capture_ix: u32,
886 pub context_capture_ix: Option<u32>,
887 pub extra_context_capture_ix: Option<u32>,
888 pub open_capture_ix: Option<u32>,
889 pub close_capture_ix: Option<u32>,
890 pub annotation_capture_ix: Option<u32>,
891}
892
893#[derive(Debug)]
894pub struct EmbeddingConfig {
895 pub query: Query,
896 pub item_capture_ix: u32,
897 pub name_capture_ix: Option<u32>,
898 pub context_capture_ix: Option<u32>,
899 pub collapse_capture_ix: Option<u32>,
900 pub keep_capture_ix: Option<u32>,
901}
902
903struct InjectionConfig {
904 query: Query,
905 content_capture_ix: u32,
906 language_capture_ix: Option<u32>,
907 patterns: Vec<InjectionPatternConfig>,
908}
909
910struct RedactionConfig {
911 pub query: Query,
912 pub redaction_capture_ix: u32,
913}
914
915#[derive(Clone, Debug, PartialEq)]
916enum RunnableCapture {
917 Named(SharedString),
918 Run,
919}
920
921struct RunnableConfig {
922 pub query: Query,
923 /// A mapping from capture indice to capture kind
924 pub extra_captures: Vec<RunnableCapture>,
925}
926
927struct OverrideConfig {
928 query: Query,
929 values: HashMap<u32, (String, LanguageConfigOverride)>,
930}
931
932#[derive(Default, Clone)]
933struct InjectionPatternConfig {
934 language: Option<Box<str>>,
935 combined: bool,
936}
937
938struct BracketConfig {
939 query: Query,
940 open_capture_ix: u32,
941 close_capture_ix: u32,
942}
943
944impl Language {
945 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
946 Self::new_with_id(LanguageId::new(), config, ts_language)
947 }
948
949 fn new_with_id(
950 id: LanguageId,
951 config: LanguageConfig,
952 ts_language: Option<tree_sitter::Language>,
953 ) -> Self {
954 Self {
955 id,
956 config,
957 grammar: ts_language.map(|ts_language| {
958 Arc::new(Grammar {
959 id: GrammarId::new(),
960 highlights_query: None,
961 brackets_config: None,
962 outline_config: None,
963 embedding_config: None,
964 indents_config: None,
965 injection_config: None,
966 override_config: None,
967 redactions_config: None,
968 runnable_config: None,
969 error_query: Query::new(&ts_language, "(ERROR) @error").unwrap(),
970 ts_language,
971 highlight_map: Default::default(),
972 })
973 }),
974 context_provider: None,
975 }
976 }
977
978 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
979 self.context_provider = provider;
980 self
981 }
982
983 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
984 if let Some(query) = queries.highlights {
985 self = self
986 .with_highlights_query(query.as_ref())
987 .context("Error loading highlights query")?;
988 }
989 if let Some(query) = queries.brackets {
990 self = self
991 .with_brackets_query(query.as_ref())
992 .context("Error loading brackets query")?;
993 }
994 if let Some(query) = queries.indents {
995 self = self
996 .with_indents_query(query.as_ref())
997 .context("Error loading indents query")?;
998 }
999 if let Some(query) = queries.outline {
1000 self = self
1001 .with_outline_query(query.as_ref())
1002 .context("Error loading outline query")?;
1003 }
1004 if let Some(query) = queries.embedding {
1005 self = self
1006 .with_embedding_query(query.as_ref())
1007 .context("Error loading embedding query")?;
1008 }
1009 if let Some(query) = queries.injections {
1010 self = self
1011 .with_injection_query(query.as_ref())
1012 .context("Error loading injection query")?;
1013 }
1014 if let Some(query) = queries.overrides {
1015 self = self
1016 .with_override_query(query.as_ref())
1017 .context("Error loading override query")?;
1018 }
1019 if let Some(query) = queries.redactions {
1020 self = self
1021 .with_redaction_query(query.as_ref())
1022 .context("Error loading redaction query")?;
1023 }
1024 if let Some(query) = queries.runnables {
1025 self = self
1026 .with_runnable_query(query.as_ref())
1027 .context("Error loading tests query")?;
1028 }
1029 Ok(self)
1030 }
1031
1032 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1033 let grammar = self
1034 .grammar_mut()
1035 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1036 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1037 Ok(self)
1038 }
1039
1040 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1041 let grammar = self
1042 .grammar_mut()
1043 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1044
1045 let query = Query::new(&grammar.ts_language, source)?;
1046 let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1047
1048 for name in query.capture_names().iter() {
1049 let kind = if *name == "run" {
1050 RunnableCapture::Run
1051 } else {
1052 RunnableCapture::Named(name.to_string().into())
1053 };
1054 extra_captures.push(kind);
1055 }
1056
1057 grammar.runnable_config = Some(RunnableConfig {
1058 extra_captures,
1059 query,
1060 });
1061
1062 Ok(self)
1063 }
1064
1065 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1066 let grammar = self
1067 .grammar_mut()
1068 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1069 let query = Query::new(&grammar.ts_language, source)?;
1070 let mut item_capture_ix = None;
1071 let mut name_capture_ix = None;
1072 let mut context_capture_ix = None;
1073 let mut extra_context_capture_ix = None;
1074 let mut open_capture_ix = None;
1075 let mut close_capture_ix = None;
1076 let mut annotation_capture_ix = None;
1077 get_capture_indices(
1078 &query,
1079 &mut [
1080 ("item", &mut item_capture_ix),
1081 ("name", &mut name_capture_ix),
1082 ("context", &mut context_capture_ix),
1083 ("context.extra", &mut extra_context_capture_ix),
1084 ("open", &mut open_capture_ix),
1085 ("close", &mut close_capture_ix),
1086 ("annotation", &mut annotation_capture_ix),
1087 ],
1088 );
1089 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1090 grammar.outline_config = Some(OutlineConfig {
1091 query,
1092 item_capture_ix,
1093 name_capture_ix,
1094 context_capture_ix,
1095 extra_context_capture_ix,
1096 open_capture_ix,
1097 close_capture_ix,
1098 annotation_capture_ix,
1099 });
1100 }
1101 Ok(self)
1102 }
1103
1104 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1105 let grammar = self
1106 .grammar_mut()
1107 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1108 let query = Query::new(&grammar.ts_language, source)?;
1109 let mut item_capture_ix = None;
1110 let mut name_capture_ix = None;
1111 let mut context_capture_ix = None;
1112 let mut collapse_capture_ix = None;
1113 let mut keep_capture_ix = None;
1114 get_capture_indices(
1115 &query,
1116 &mut [
1117 ("item", &mut item_capture_ix),
1118 ("name", &mut name_capture_ix),
1119 ("context", &mut context_capture_ix),
1120 ("keep", &mut keep_capture_ix),
1121 ("collapse", &mut collapse_capture_ix),
1122 ],
1123 );
1124 if let Some(item_capture_ix) = item_capture_ix {
1125 grammar.embedding_config = Some(EmbeddingConfig {
1126 query,
1127 item_capture_ix,
1128 name_capture_ix,
1129 context_capture_ix,
1130 collapse_capture_ix,
1131 keep_capture_ix,
1132 });
1133 }
1134 Ok(self)
1135 }
1136
1137 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1138 let grammar = self
1139 .grammar_mut()
1140 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1141 let query = Query::new(&grammar.ts_language, source)?;
1142 let mut open_capture_ix = None;
1143 let mut close_capture_ix = None;
1144 get_capture_indices(
1145 &query,
1146 &mut [
1147 ("open", &mut open_capture_ix),
1148 ("close", &mut close_capture_ix),
1149 ],
1150 );
1151 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1152 grammar.brackets_config = Some(BracketConfig {
1153 query,
1154 open_capture_ix,
1155 close_capture_ix,
1156 });
1157 }
1158 Ok(self)
1159 }
1160
1161 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1162 let grammar = self
1163 .grammar_mut()
1164 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1165 let query = Query::new(&grammar.ts_language, source)?;
1166 let mut indent_capture_ix = None;
1167 let mut start_capture_ix = None;
1168 let mut end_capture_ix = None;
1169 let mut outdent_capture_ix = None;
1170 get_capture_indices(
1171 &query,
1172 &mut [
1173 ("indent", &mut indent_capture_ix),
1174 ("start", &mut start_capture_ix),
1175 ("end", &mut end_capture_ix),
1176 ("outdent", &mut outdent_capture_ix),
1177 ],
1178 );
1179 if let Some(indent_capture_ix) = indent_capture_ix {
1180 grammar.indents_config = Some(IndentConfig {
1181 query,
1182 indent_capture_ix,
1183 start_capture_ix,
1184 end_capture_ix,
1185 outdent_capture_ix,
1186 });
1187 }
1188 Ok(self)
1189 }
1190
1191 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1192 let grammar = self
1193 .grammar_mut()
1194 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1195 let query = Query::new(&grammar.ts_language, source)?;
1196 let mut language_capture_ix = None;
1197 let mut content_capture_ix = None;
1198 get_capture_indices(
1199 &query,
1200 &mut [
1201 ("language", &mut language_capture_ix),
1202 ("content", &mut content_capture_ix),
1203 ],
1204 );
1205 let patterns = (0..query.pattern_count())
1206 .map(|ix| {
1207 let mut config = InjectionPatternConfig::default();
1208 for setting in query.property_settings(ix) {
1209 match setting.key.as_ref() {
1210 "language" => {
1211 config.language.clone_from(&setting.value);
1212 }
1213 "combined" => {
1214 config.combined = true;
1215 }
1216 _ => {}
1217 }
1218 }
1219 config
1220 })
1221 .collect();
1222 if let Some(content_capture_ix) = content_capture_ix {
1223 grammar.injection_config = Some(InjectionConfig {
1224 query,
1225 language_capture_ix,
1226 content_capture_ix,
1227 patterns,
1228 });
1229 }
1230 Ok(self)
1231 }
1232
1233 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1234 let query = {
1235 let grammar = self
1236 .grammar
1237 .as_ref()
1238 .ok_or_else(|| anyhow!("no grammar for language"))?;
1239 Query::new(&grammar.ts_language, source)?
1240 };
1241
1242 let mut override_configs_by_id = HashMap::default();
1243 for (ix, name) in query.capture_names().iter().enumerate() {
1244 if !name.starts_with('_') {
1245 let value = self.config.overrides.remove(*name).unwrap_or_default();
1246 for server_name in &value.opt_into_language_servers {
1247 if !self
1248 .config
1249 .scope_opt_in_language_servers
1250 .contains(server_name)
1251 {
1252 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1253 }
1254 }
1255
1256 override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1257 }
1258 }
1259
1260 if !self.config.overrides.is_empty() {
1261 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1262 Err(anyhow!(
1263 "language {:?} has overrides in config not in query: {keys:?}",
1264 self.config.name
1265 ))?;
1266 }
1267
1268 for disabled_scope_name in self
1269 .config
1270 .brackets
1271 .disabled_scopes_by_bracket_ix
1272 .iter()
1273 .flatten()
1274 {
1275 if !override_configs_by_id
1276 .values()
1277 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1278 {
1279 Err(anyhow!(
1280 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1281 self.config.name
1282 ))?;
1283 }
1284 }
1285
1286 for (name, override_config) in override_configs_by_id.values_mut() {
1287 override_config.disabled_bracket_ixs = self
1288 .config
1289 .brackets
1290 .disabled_scopes_by_bracket_ix
1291 .iter()
1292 .enumerate()
1293 .filter_map(|(ix, disabled_scope_names)| {
1294 if disabled_scope_names.contains(name) {
1295 Some(ix as u16)
1296 } else {
1297 None
1298 }
1299 })
1300 .collect();
1301 }
1302
1303 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1304
1305 let grammar = self
1306 .grammar_mut()
1307 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1308 grammar.override_config = Some(OverrideConfig {
1309 query,
1310 values: override_configs_by_id,
1311 });
1312 Ok(self)
1313 }
1314
1315 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1316 let grammar = self
1317 .grammar_mut()
1318 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1319
1320 let query = Query::new(&grammar.ts_language, source)?;
1321 let mut redaction_capture_ix = None;
1322 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1323
1324 if let Some(redaction_capture_ix) = redaction_capture_ix {
1325 grammar.redactions_config = Some(RedactionConfig {
1326 query,
1327 redaction_capture_ix,
1328 });
1329 }
1330
1331 Ok(self)
1332 }
1333
1334 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1335 Arc::get_mut(self.grammar.as_mut()?)
1336 }
1337
1338 pub fn name(&self) -> Arc<str> {
1339 self.config.name.clone()
1340 }
1341
1342 pub fn code_fence_block_name(&self) -> Arc<str> {
1343 self.config
1344 .code_fence_block_name
1345 .clone()
1346 .unwrap_or_else(|| self.config.name.to_lowercase().into())
1347 }
1348
1349 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1350 self.context_provider.clone()
1351 }
1352
1353 pub fn highlight_text<'a>(
1354 self: &'a Arc<Self>,
1355 text: &'a Rope,
1356 range: Range<usize>,
1357 ) -> Vec<(Range<usize>, HighlightId)> {
1358 let mut result = Vec::new();
1359 if let Some(grammar) = &self.grammar {
1360 let tree = grammar.parse_text(text, None);
1361 let captures =
1362 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1363 grammar.highlights_query.as_ref()
1364 });
1365 let highlight_maps = vec![grammar.highlight_map()];
1366 let mut offset = 0;
1367 for chunk in
1368 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1369 {
1370 let end_offset = offset + chunk.text.len();
1371 if let Some(highlight_id) = chunk.syntax_highlight_id {
1372 if !highlight_id.is_default() {
1373 result.push((offset..end_offset, highlight_id));
1374 }
1375 }
1376 offset = end_offset;
1377 }
1378 }
1379 result
1380 }
1381
1382 pub fn path_suffixes(&self) -> &[String] {
1383 &self.config.matcher.path_suffixes
1384 }
1385
1386 pub fn should_autoclose_before(&self, c: char) -> bool {
1387 c.is_whitespace() || self.config.autoclose_before.contains(c)
1388 }
1389
1390 pub fn set_theme(&self, theme: &SyntaxTheme) {
1391 if let Some(grammar) = self.grammar.as_ref() {
1392 if let Some(highlights_query) = &grammar.highlights_query {
1393 *grammar.highlight_map.lock() =
1394 HighlightMap::new(highlights_query.capture_names(), theme);
1395 }
1396 }
1397 }
1398
1399 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1400 self.grammar.as_ref()
1401 }
1402
1403 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1404 LanguageScope {
1405 language: self.clone(),
1406 override_id: None,
1407 }
1408 }
1409
1410 pub fn lsp_id(&self) -> String {
1411 match self.config.name.as_ref() {
1412 "Plain Text" => "plaintext".to_string(),
1413 language_name => language_name.to_lowercase(),
1414 }
1415 }
1416
1417 pub fn prettier_parser_name(&self) -> Option<&str> {
1418 self.config.prettier_parser_name.as_deref()
1419 }
1420}
1421
1422impl LanguageScope {
1423 pub fn language_name(&self) -> Arc<str> {
1424 self.language.config.name.clone()
1425 }
1426
1427 pub fn collapsed_placeholder(&self) -> &str {
1428 self.language.config.collapsed_placeholder.as_ref()
1429 }
1430
1431 /// Returns line prefix that is inserted in e.g. line continuations or
1432 /// in `toggle comments` action.
1433 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1434 Override::as_option(
1435 self.config_override().map(|o| &o.line_comments),
1436 Some(&self.language.config.line_comments),
1437 )
1438 .map_or(&[] as &[_], |e| e.as_slice())
1439 }
1440
1441 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1442 Override::as_option(
1443 self.config_override().map(|o| &o.block_comment),
1444 self.language.config.block_comment.as_ref(),
1445 )
1446 .map(|e| (&e.0, &e.1))
1447 }
1448
1449 /// Returns a list of language-specific word characters.
1450 ///
1451 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1452 /// the purpose of actions like 'move to next word end` or whole-word search.
1453 /// It additionally accounts for language's additional word characters.
1454 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1455 Override::as_option(
1456 self.config_override().map(|o| &o.word_characters),
1457 Some(&self.language.config.word_characters),
1458 )
1459 }
1460
1461 /// Returns a list of bracket pairs for a given language with an additional
1462 /// piece of information about whether the particular bracket pair is currently active for a given language.
1463 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1464 let mut disabled_ids = self
1465 .config_override()
1466 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1467 self.language
1468 .config
1469 .brackets
1470 .pairs
1471 .iter()
1472 .enumerate()
1473 .map(move |(ix, bracket)| {
1474 let mut is_enabled = true;
1475 if let Some(next_disabled_ix) = disabled_ids.first() {
1476 if ix == *next_disabled_ix as usize {
1477 disabled_ids = &disabled_ids[1..];
1478 is_enabled = false;
1479 }
1480 }
1481 (bracket, is_enabled)
1482 })
1483 }
1484
1485 pub fn should_autoclose_before(&self, c: char) -> bool {
1486 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1487 }
1488
1489 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1490 let config = &self.language.config;
1491 let opt_in_servers = &config.scope_opt_in_language_servers;
1492 if opt_in_servers.iter().any(|o| *o == *name.0) {
1493 if let Some(over) = self.config_override() {
1494 over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1495 } else {
1496 false
1497 }
1498 } else {
1499 true
1500 }
1501 }
1502
1503 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1504 let id = self.override_id?;
1505 let grammar = self.language.grammar.as_ref()?;
1506 let override_config = grammar.override_config.as_ref()?;
1507 override_config.values.get(&id).map(|e| &e.1)
1508 }
1509}
1510
1511impl Hash for Language {
1512 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1513 self.id.hash(state)
1514 }
1515}
1516
1517impl PartialEq for Language {
1518 fn eq(&self, other: &Self) -> bool {
1519 self.id.eq(&other.id)
1520 }
1521}
1522
1523impl Eq for Language {}
1524
1525impl Debug for Language {
1526 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1527 f.debug_struct("Language")
1528 .field("name", &self.config.name)
1529 .finish()
1530 }
1531}
1532
1533impl Grammar {
1534 pub fn id(&self) -> GrammarId {
1535 self.id
1536 }
1537
1538 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1539 with_parser(|parser| {
1540 parser
1541 .set_language(&self.ts_language)
1542 .expect("incompatible grammar");
1543 let mut chunks = text.chunks_in_range(0..text.len());
1544 parser
1545 .parse_with(
1546 &mut move |offset, _| {
1547 chunks.seek(offset);
1548 chunks.next().unwrap_or("").as_bytes()
1549 },
1550 old_tree.as_ref(),
1551 )
1552 .unwrap()
1553 })
1554 }
1555
1556 pub fn highlight_map(&self) -> HighlightMap {
1557 self.highlight_map.lock().clone()
1558 }
1559
1560 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1561 let capture_id = self
1562 .highlights_query
1563 .as_ref()?
1564 .capture_index_for_name(name)?;
1565 Some(self.highlight_map.lock().get(capture_id))
1566 }
1567}
1568
1569impl CodeLabel {
1570 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1571 let mut result = Self {
1572 runs: Vec::new(),
1573 filter_range: 0..text.len(),
1574 text,
1575 };
1576 if let Some(filter_text) = filter_text {
1577 if let Some(ix) = result.text.find(filter_text) {
1578 result.filter_range = ix..ix + filter_text.len();
1579 }
1580 }
1581 result
1582 }
1583
1584 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1585 let start_ix = self.text.len();
1586 self.text.push_str(text);
1587 let end_ix = self.text.len();
1588 if let Some(highlight) = highlight {
1589 self.runs.push((start_ix..end_ix, highlight));
1590 }
1591 }
1592
1593 pub fn text(&self) -> &str {
1594 self.text.as_str()
1595 }
1596}
1597
1598impl From<String> for CodeLabel {
1599 fn from(value: String) -> Self {
1600 Self::plain(value, None)
1601 }
1602}
1603
1604impl From<&str> for CodeLabel {
1605 fn from(value: &str) -> Self {
1606 Self::plain(value.to_string(), None)
1607 }
1608}
1609
1610impl Ord for LanguageMatcher {
1611 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1612 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1613 self.first_line_pattern
1614 .as_ref()
1615 .map(Regex::as_str)
1616 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1617 })
1618 }
1619}
1620
1621impl PartialOrd for LanguageMatcher {
1622 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1623 Some(self.cmp(other))
1624 }
1625}
1626
1627impl Eq for LanguageMatcher {}
1628
1629impl PartialEq for LanguageMatcher {
1630 fn eq(&self, other: &Self) -> bool {
1631 self.path_suffixes == other.path_suffixes
1632 && self.first_line_pattern.as_ref().map(Regex::as_str)
1633 == other.first_line_pattern.as_ref().map(Regex::as_str)
1634 }
1635}
1636
1637#[cfg(any(test, feature = "test-support"))]
1638impl Default for FakeLspAdapter {
1639 fn default() -> Self {
1640 Self {
1641 name: "the-fake-language-server",
1642 capabilities: lsp::LanguageServer::full_capabilities(),
1643 initializer: None,
1644 disk_based_diagnostics_progress_token: None,
1645 initialization_options: None,
1646 disk_based_diagnostics_sources: Vec::new(),
1647 prettier_plugins: Vec::new(),
1648 language_server_binary: LanguageServerBinary {
1649 path: "/the/fake/lsp/path".into(),
1650 arguments: vec![],
1651 env: Default::default(),
1652 },
1653 }
1654 }
1655}
1656
1657#[cfg(any(test, feature = "test-support"))]
1658#[async_trait(?Send)]
1659impl LspAdapter for FakeLspAdapter {
1660 fn name(&self) -> LanguageServerName {
1661 LanguageServerName(self.name.into())
1662 }
1663
1664 fn get_language_server_command<'a>(
1665 self: Arc<Self>,
1666 _: Arc<Language>,
1667 _: Arc<Path>,
1668 _: Arc<dyn LspAdapterDelegate>,
1669 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1670 _: &'a mut AsyncAppContext,
1671 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1672 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1673 }
1674
1675 async fn fetch_latest_server_version(
1676 &self,
1677 _: &dyn LspAdapterDelegate,
1678 ) -> Result<Box<dyn 'static + Send + Any>> {
1679 unreachable!();
1680 }
1681
1682 async fn fetch_server_binary(
1683 &self,
1684 _: Box<dyn 'static + Send + Any>,
1685 _: PathBuf,
1686 _: &dyn LspAdapterDelegate,
1687 ) -> Result<LanguageServerBinary> {
1688 unreachable!();
1689 }
1690
1691 async fn cached_server_binary(
1692 &self,
1693 _: PathBuf,
1694 _: &dyn LspAdapterDelegate,
1695 ) -> Option<LanguageServerBinary> {
1696 unreachable!();
1697 }
1698
1699 async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1700 unreachable!();
1701 }
1702
1703 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1704
1705 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1706 self.disk_based_diagnostics_sources.clone()
1707 }
1708
1709 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1710 self.disk_based_diagnostics_progress_token.clone()
1711 }
1712
1713 async fn initialization_options(
1714 self: Arc<Self>,
1715 _: &Arc<dyn LspAdapterDelegate>,
1716 ) -> Result<Option<Value>> {
1717 Ok(self.initialization_options.clone())
1718 }
1719
1720 fn as_fake(&self) -> Option<&FakeLspAdapter> {
1721 Some(self)
1722 }
1723}
1724
1725fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1726 for (ix, name) in query.capture_names().iter().enumerate() {
1727 for (capture_name, index) in captures.iter_mut() {
1728 if capture_name == name {
1729 **index = Some(ix as u32);
1730 break;
1731 }
1732 }
1733 }
1734}
1735
1736pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1737 lsp::Position::new(point.row, point.column)
1738}
1739
1740pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1741 Unclipped(PointUtf16::new(point.line, point.character))
1742}
1743
1744pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1745 lsp::Range {
1746 start: point_to_lsp(range.start),
1747 end: point_to_lsp(range.end),
1748 }
1749}
1750
1751pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1752 let mut start = point_from_lsp(range.start);
1753 let mut end = point_from_lsp(range.end);
1754 if start > end {
1755 mem::swap(&mut start, &mut end);
1756 }
1757 start..end
1758}
1759
1760#[cfg(test)]
1761mod tests {
1762 use super::*;
1763 use gpui::TestAppContext;
1764
1765 #[gpui::test(iterations = 10)]
1766 async fn test_language_loading(cx: &mut TestAppContext) {
1767 let languages = LanguageRegistry::test(cx.executor());
1768 let languages = Arc::new(languages);
1769 languages.register_native_grammars([
1770 ("json", tree_sitter_json::language()),
1771 ("rust", tree_sitter_rust::language()),
1772 ]);
1773 languages.register_test_language(LanguageConfig {
1774 name: "JSON".into(),
1775 grammar: Some("json".into()),
1776 matcher: LanguageMatcher {
1777 path_suffixes: vec!["json".into()],
1778 ..Default::default()
1779 },
1780 ..Default::default()
1781 });
1782 languages.register_test_language(LanguageConfig {
1783 name: "Rust".into(),
1784 grammar: Some("rust".into()),
1785 matcher: LanguageMatcher {
1786 path_suffixes: vec!["rs".into()],
1787 ..Default::default()
1788 },
1789 ..Default::default()
1790 });
1791 assert_eq!(
1792 languages.language_names(),
1793 &[
1794 "JSON".to_string(),
1795 "Plain Text".to_string(),
1796 "Rust".to_string(),
1797 ]
1798 );
1799
1800 let rust1 = languages.language_for_name("Rust");
1801 let rust2 = languages.language_for_name("Rust");
1802
1803 // Ensure language is still listed even if it's being loaded.
1804 assert_eq!(
1805 languages.language_names(),
1806 &[
1807 "JSON".to_string(),
1808 "Plain Text".to_string(),
1809 "Rust".to_string(),
1810 ]
1811 );
1812
1813 let (rust1, rust2) = futures::join!(rust1, rust2);
1814 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1815
1816 // Ensure language is still listed even after loading it.
1817 assert_eq!(
1818 languages.language_names(),
1819 &[
1820 "JSON".to_string(),
1821 "Plain Text".to_string(),
1822 "Rust".to_string(),
1823 ]
1824 );
1825
1826 // Loading an unknown language returns an error.
1827 assert!(languages.language_for_name("Unknown").await.is_err());
1828 }
1829}