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