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