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