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