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.grammar_mut();
950 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
951 Ok(self)
952 }
953
954 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
955 let grammar = self.grammar_mut();
956 let query = Query::new(&grammar.ts_language, source)?;
957 let mut item_capture_ix = None;
958 let mut name_capture_ix = None;
959 let mut context_capture_ix = None;
960 let mut extra_context_capture_ix = None;
961 get_capture_indices(
962 &query,
963 &mut [
964 ("item", &mut item_capture_ix),
965 ("name", &mut name_capture_ix),
966 ("context", &mut context_capture_ix),
967 ("context.extra", &mut extra_context_capture_ix),
968 ],
969 );
970 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
971 grammar.outline_config = Some(OutlineConfig {
972 query,
973 item_capture_ix,
974 name_capture_ix,
975 context_capture_ix,
976 extra_context_capture_ix,
977 });
978 }
979 Ok(self)
980 }
981
982 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
983 let grammar = self.grammar_mut();
984 let query = Query::new(&grammar.ts_language, source)?;
985 let mut item_capture_ix = None;
986 let mut name_capture_ix = None;
987 let mut context_capture_ix = None;
988 let mut collapse_capture_ix = None;
989 let mut keep_capture_ix = None;
990 get_capture_indices(
991 &query,
992 &mut [
993 ("item", &mut item_capture_ix),
994 ("name", &mut name_capture_ix),
995 ("context", &mut context_capture_ix),
996 ("keep", &mut keep_capture_ix),
997 ("collapse", &mut collapse_capture_ix),
998 ],
999 );
1000 if let Some(item_capture_ix) = item_capture_ix {
1001 grammar.embedding_config = Some(EmbeddingConfig {
1002 query,
1003 item_capture_ix,
1004 name_capture_ix,
1005 context_capture_ix,
1006 collapse_capture_ix,
1007 keep_capture_ix,
1008 });
1009 }
1010 Ok(self)
1011 }
1012
1013 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1014 let grammar = self.grammar_mut();
1015 let query = Query::new(&grammar.ts_language, source)?;
1016 let mut open_capture_ix = None;
1017 let mut close_capture_ix = None;
1018 get_capture_indices(
1019 &query,
1020 &mut [
1021 ("open", &mut open_capture_ix),
1022 ("close", &mut close_capture_ix),
1023 ],
1024 );
1025 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1026 grammar.brackets_config = Some(BracketConfig {
1027 query,
1028 open_capture_ix,
1029 close_capture_ix,
1030 });
1031 }
1032 Ok(self)
1033 }
1034
1035 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1036 let grammar = self.grammar_mut();
1037 let query = Query::new(&grammar.ts_language, source)?;
1038 let mut indent_capture_ix = None;
1039 let mut start_capture_ix = None;
1040 let mut end_capture_ix = None;
1041 let mut outdent_capture_ix = None;
1042 get_capture_indices(
1043 &query,
1044 &mut [
1045 ("indent", &mut indent_capture_ix),
1046 ("start", &mut start_capture_ix),
1047 ("end", &mut end_capture_ix),
1048 ("outdent", &mut outdent_capture_ix),
1049 ],
1050 );
1051 if let Some(indent_capture_ix) = indent_capture_ix {
1052 grammar.indents_config = Some(IndentConfig {
1053 query,
1054 indent_capture_ix,
1055 start_capture_ix,
1056 end_capture_ix,
1057 outdent_capture_ix,
1058 });
1059 }
1060 Ok(self)
1061 }
1062
1063 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1064 let grammar = self.grammar_mut();
1065 let query = Query::new(&grammar.ts_language, source)?;
1066 let mut language_capture_ix = None;
1067 let mut content_capture_ix = None;
1068 get_capture_indices(
1069 &query,
1070 &mut [
1071 ("language", &mut language_capture_ix),
1072 ("content", &mut content_capture_ix),
1073 ],
1074 );
1075 let patterns = (0..query.pattern_count())
1076 .map(|ix| {
1077 let mut config = InjectionPatternConfig::default();
1078 for setting in query.property_settings(ix) {
1079 match setting.key.as_ref() {
1080 "language" => {
1081 config.language = setting.value.clone();
1082 }
1083 "combined" => {
1084 config.combined = true;
1085 }
1086 _ => {}
1087 }
1088 }
1089 config
1090 })
1091 .collect();
1092 if let Some(content_capture_ix) = content_capture_ix {
1093 grammar.injection_config = Some(InjectionConfig {
1094 query,
1095 language_capture_ix,
1096 content_capture_ix,
1097 patterns,
1098 });
1099 }
1100 Ok(self)
1101 }
1102
1103 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1104 let query = Query::new(&self.grammar_mut().ts_language, source)?;
1105
1106 let mut override_configs_by_id = HashMap::default();
1107 for (ix, name) in query.capture_names().iter().enumerate() {
1108 if !name.starts_with('_') {
1109 let value = self.config.overrides.remove(*name).unwrap_or_default();
1110 for server_name in &value.opt_into_language_servers {
1111 if !self
1112 .config
1113 .scope_opt_in_language_servers
1114 .contains(server_name)
1115 {
1116 util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
1117 }
1118 }
1119
1120 override_configs_by_id.insert(ix as u32, (name.to_string(), value));
1121 }
1122 }
1123
1124 if !self.config.overrides.is_empty() {
1125 let keys = self.config.overrides.keys().collect::<Vec<_>>();
1126 Err(anyhow!(
1127 "language {:?} has overrides in config not in query: {keys:?}",
1128 self.config.name
1129 ))?;
1130 }
1131
1132 for disabled_scope_name in self
1133 .config
1134 .brackets
1135 .disabled_scopes_by_bracket_ix
1136 .iter()
1137 .flatten()
1138 {
1139 if !override_configs_by_id
1140 .values()
1141 .any(|(scope_name, _)| scope_name == disabled_scope_name)
1142 {
1143 Err(anyhow!(
1144 "language {:?} has overrides in config not in query: {disabled_scope_name:?}",
1145 self.config.name
1146 ))?;
1147 }
1148 }
1149
1150 for (name, override_config) in override_configs_by_id.values_mut() {
1151 override_config.disabled_bracket_ixs = self
1152 .config
1153 .brackets
1154 .disabled_scopes_by_bracket_ix
1155 .iter()
1156 .enumerate()
1157 .filter_map(|(ix, disabled_scope_names)| {
1158 if disabled_scope_names.contains(name) {
1159 Some(ix as u16)
1160 } else {
1161 None
1162 }
1163 })
1164 .collect();
1165 }
1166
1167 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1168 self.grammar_mut().override_config = Some(OverrideConfig {
1169 query,
1170 values: override_configs_by_id,
1171 });
1172 Ok(self)
1173 }
1174
1175 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1176 let grammar = self.grammar_mut();
1177 let query = Query::new(&grammar.ts_language, source)?;
1178 let mut redaction_capture_ix = None;
1179 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1180
1181 if let Some(redaction_capture_ix) = redaction_capture_ix {
1182 grammar.redactions_config = Some(RedactionConfig {
1183 query,
1184 redaction_capture_ix,
1185 });
1186 }
1187
1188 Ok(self)
1189 }
1190
1191 fn grammar_mut(&mut self) -> &mut Grammar {
1192 Arc::get_mut(self.grammar.as_mut().unwrap()).unwrap()
1193 }
1194
1195 pub fn name(&self) -> Arc<str> {
1196 self.config.name.clone()
1197 }
1198
1199 pub fn context_provider(&self) -> Option<Arc<dyn LanguageContextProvider>> {
1200 self.context_provider.clone()
1201 }
1202
1203 pub fn highlight_text<'a>(
1204 self: &'a Arc<Self>,
1205 text: &'a Rope,
1206 range: Range<usize>,
1207 ) -> Vec<(Range<usize>, HighlightId)> {
1208 let mut result = Vec::new();
1209 if let Some(grammar) = &self.grammar {
1210 let tree = grammar.parse_text(text, None);
1211 let captures =
1212 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1213 grammar.highlights_query.as_ref()
1214 });
1215 let highlight_maps = vec![grammar.highlight_map()];
1216 let mut offset = 0;
1217 for chunk in BufferChunks::new(text, range, Some((captures, highlight_maps)), vec![]) {
1218 let end_offset = offset + chunk.text.len();
1219 if let Some(highlight_id) = chunk.syntax_highlight_id {
1220 if !highlight_id.is_default() {
1221 result.push((offset..end_offset, highlight_id));
1222 }
1223 }
1224 offset = end_offset;
1225 }
1226 }
1227 result
1228 }
1229
1230 pub fn path_suffixes(&self) -> &[String] {
1231 &self.config.matcher.path_suffixes
1232 }
1233
1234 pub fn should_autoclose_before(&self, c: char) -> bool {
1235 c.is_whitespace() || self.config.autoclose_before.contains(c)
1236 }
1237
1238 pub fn set_theme(&self, theme: &SyntaxTheme) {
1239 if let Some(grammar) = self.grammar.as_ref() {
1240 if let Some(highlights_query) = &grammar.highlights_query {
1241 *grammar.highlight_map.lock() =
1242 HighlightMap::new(highlights_query.capture_names(), theme);
1243 }
1244 }
1245 }
1246
1247 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1248 self.grammar.as_ref()
1249 }
1250
1251 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1252 LanguageScope {
1253 language: self.clone(),
1254 override_id: None,
1255 }
1256 }
1257
1258 pub fn prettier_parser_name(&self) -> Option<&str> {
1259 self.config.prettier_parser_name.as_deref()
1260 }
1261}
1262
1263impl LanguageScope {
1264 pub fn collapsed_placeholder(&self) -> &str {
1265 self.language.config.collapsed_placeholder.as_ref()
1266 }
1267
1268 /// Returns line prefix that is inserted in e.g. line continuations or
1269 /// in `toggle comments` action.
1270 pub fn line_comment_prefixes(&self) -> Option<&Vec<Arc<str>>> {
1271 Override::as_option(
1272 self.config_override().map(|o| &o.line_comments),
1273 Some(&self.language.config.line_comments),
1274 )
1275 }
1276
1277 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1278 Override::as_option(
1279 self.config_override().map(|o| &o.block_comment),
1280 self.language.config.block_comment.as_ref(),
1281 )
1282 .map(|e| (&e.0, &e.1))
1283 }
1284
1285 /// Returns a list of language-specific word characters.
1286 ///
1287 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1288 /// the purpose of actions like 'move to next word end` or whole-word search.
1289 /// It additionally accounts for language's additional word characters.
1290 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1291 Override::as_option(
1292 self.config_override().map(|o| &o.word_characters),
1293 Some(&self.language.config.word_characters),
1294 )
1295 }
1296
1297 /// Returns a list of bracket pairs for a given language with an additional
1298 /// piece of information about whether the particular bracket pair is currently active for a given language.
1299 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1300 let mut disabled_ids = self
1301 .config_override()
1302 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1303 self.language
1304 .config
1305 .brackets
1306 .pairs
1307 .iter()
1308 .enumerate()
1309 .map(move |(ix, bracket)| {
1310 let mut is_enabled = true;
1311 if let Some(next_disabled_ix) = disabled_ids.first() {
1312 if ix == *next_disabled_ix as usize {
1313 disabled_ids = &disabled_ids[1..];
1314 is_enabled = false;
1315 }
1316 }
1317 (bracket, is_enabled)
1318 })
1319 }
1320
1321 pub fn should_autoclose_before(&self, c: char) -> bool {
1322 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1323 }
1324
1325 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1326 let config = &self.language.config;
1327 let opt_in_servers = &config.scope_opt_in_language_servers;
1328 if opt_in_servers.iter().any(|o| *o == *name.0) {
1329 if let Some(over) = self.config_override() {
1330 over.opt_into_language_servers.iter().any(|o| *o == *name.0)
1331 } else {
1332 false
1333 }
1334 } else {
1335 true
1336 }
1337 }
1338
1339 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1340 let id = self.override_id?;
1341 let grammar = self.language.grammar.as_ref()?;
1342 let override_config = grammar.override_config.as_ref()?;
1343 override_config.values.get(&id).map(|e| &e.1)
1344 }
1345}
1346
1347impl Hash for Language {
1348 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1349 self.id.hash(state)
1350 }
1351}
1352
1353impl PartialEq for Language {
1354 fn eq(&self, other: &Self) -> bool {
1355 self.id.eq(&other.id)
1356 }
1357}
1358
1359impl Eq for Language {}
1360
1361impl Debug for Language {
1362 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1363 f.debug_struct("Language")
1364 .field("name", &self.config.name)
1365 .finish()
1366 }
1367}
1368
1369impl Grammar {
1370 pub fn id(&self) -> GrammarId {
1371 self.id
1372 }
1373
1374 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1375 PARSER.with(|parser| {
1376 let mut parser = parser.borrow_mut();
1377 parser
1378 .set_language(&self.ts_language)
1379 .expect("incompatible grammar");
1380 let mut chunks = text.chunks_in_range(0..text.len());
1381 parser
1382 .parse_with(
1383 &mut move |offset, _| {
1384 chunks.seek(offset);
1385 chunks.next().unwrap_or("").as_bytes()
1386 },
1387 old_tree.as_ref(),
1388 )
1389 .unwrap()
1390 })
1391 }
1392
1393 pub fn highlight_map(&self) -> HighlightMap {
1394 self.highlight_map.lock().clone()
1395 }
1396
1397 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1398 let capture_id = self
1399 .highlights_query
1400 .as_ref()?
1401 .capture_index_for_name(name)?;
1402 Some(self.highlight_map.lock().get(capture_id))
1403 }
1404}
1405
1406impl CodeLabel {
1407 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1408 let mut result = Self {
1409 runs: Vec::new(),
1410 filter_range: 0..text.len(),
1411 text,
1412 };
1413 if let Some(filter_text) = filter_text {
1414 if let Some(ix) = result.text.find(filter_text) {
1415 result.filter_range = ix..ix + filter_text.len();
1416 }
1417 }
1418 result
1419 }
1420}
1421
1422impl Ord for LanguageMatcher {
1423 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1424 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1425 self.first_line_pattern
1426 .as_ref()
1427 .map(Regex::as_str)
1428 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1429 })
1430 }
1431}
1432
1433impl PartialOrd for LanguageMatcher {
1434 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1435 Some(self.cmp(other))
1436 }
1437}
1438
1439impl Eq for LanguageMatcher {}
1440
1441impl PartialEq for LanguageMatcher {
1442 fn eq(&self, other: &Self) -> bool {
1443 self.path_suffixes == other.path_suffixes
1444 && self.first_line_pattern.as_ref().map(Regex::as_str)
1445 == other.first_line_pattern.as_ref().map(Regex::as_str)
1446 }
1447}
1448
1449#[cfg(any(test, feature = "test-support"))]
1450impl Default for FakeLspAdapter {
1451 fn default() -> Self {
1452 Self {
1453 name: "the-fake-language-server",
1454 capabilities: lsp::LanguageServer::full_capabilities(),
1455 initializer: None,
1456 disk_based_diagnostics_progress_token: None,
1457 initialization_options: None,
1458 disk_based_diagnostics_sources: Vec::new(),
1459 prettier_plugins: Vec::new(),
1460 language_server_binary: LanguageServerBinary {
1461 path: "/the/fake/lsp/path".into(),
1462 arguments: vec![],
1463 env: Default::default(),
1464 },
1465 }
1466 }
1467}
1468
1469#[cfg(any(test, feature = "test-support"))]
1470#[async_trait(?Send)]
1471impl LspAdapter for FakeLspAdapter {
1472 fn name(&self) -> LanguageServerName {
1473 LanguageServerName(self.name.into())
1474 }
1475
1476 fn get_language_server_command<'a>(
1477 self: Arc<Self>,
1478 _: Arc<Language>,
1479 _: Arc<Path>,
1480 _: Arc<dyn LspAdapterDelegate>,
1481 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
1482 _: &'a mut AsyncAppContext,
1483 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
1484 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
1485 }
1486
1487 async fn fetch_latest_server_version(
1488 &self,
1489 _: &dyn LspAdapterDelegate,
1490 ) -> Result<Box<dyn 'static + Send + Any>> {
1491 unreachable!();
1492 }
1493
1494 async fn fetch_server_binary(
1495 &self,
1496 _: Box<dyn 'static + Send + Any>,
1497 _: PathBuf,
1498 _: &dyn LspAdapterDelegate,
1499 ) -> Result<LanguageServerBinary> {
1500 unreachable!();
1501 }
1502
1503 async fn cached_server_binary(
1504 &self,
1505 _: PathBuf,
1506 _: &dyn LspAdapterDelegate,
1507 ) -> Option<LanguageServerBinary> {
1508 unreachable!();
1509 }
1510
1511 async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
1512 unreachable!();
1513 }
1514
1515 fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
1516
1517 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
1518 self.disk_based_diagnostics_sources.clone()
1519 }
1520
1521 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
1522 self.disk_based_diagnostics_progress_token.clone()
1523 }
1524
1525 fn initialization_options(&self) -> Option<Value> {
1526 self.initialization_options.clone()
1527 }
1528
1529 fn prettier_plugins(&self) -> &[&'static str] {
1530 &self.prettier_plugins
1531 }
1532
1533 fn as_fake(&self) -> Option<&FakeLspAdapter> {
1534 Some(self)
1535 }
1536}
1537
1538fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
1539 for (ix, name) in query.capture_names().iter().enumerate() {
1540 for (capture_name, index) in captures.iter_mut() {
1541 if capture_name == name {
1542 **index = Some(ix as u32);
1543 break;
1544 }
1545 }
1546 }
1547}
1548
1549pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
1550 lsp::Position::new(point.row, point.column)
1551}
1552
1553pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
1554 Unclipped(PointUtf16::new(point.line, point.character))
1555}
1556
1557pub fn range_to_lsp(range: Range<PointUtf16>) -> lsp::Range {
1558 lsp::Range {
1559 start: point_to_lsp(range.start),
1560 end: point_to_lsp(range.end),
1561 }
1562}
1563
1564pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
1565 let mut start = point_from_lsp(range.start);
1566 let mut end = point_from_lsp(range.end);
1567 if start > end {
1568 mem::swap(&mut start, &mut end);
1569 }
1570 start..end
1571}
1572
1573#[cfg(test)]
1574mod tests {
1575 use super::*;
1576 use gpui::TestAppContext;
1577
1578 #[gpui::test(iterations = 10)]
1579 async fn test_language_loading(cx: &mut TestAppContext) {
1580 let languages = LanguageRegistry::test(cx.executor());
1581 let languages = Arc::new(languages);
1582 languages.register_native_grammars([
1583 ("json", tree_sitter_json::language()),
1584 ("rust", tree_sitter_rust::language()),
1585 ]);
1586 languages.register_test_language(LanguageConfig {
1587 name: "JSON".into(),
1588 grammar: Some("json".into()),
1589 matcher: LanguageMatcher {
1590 path_suffixes: vec!["json".into()],
1591 ..Default::default()
1592 },
1593 ..Default::default()
1594 });
1595 languages.register_test_language(LanguageConfig {
1596 name: "Rust".into(),
1597 grammar: Some("rust".into()),
1598 matcher: LanguageMatcher {
1599 path_suffixes: vec!["rs".into()],
1600 ..Default::default()
1601 },
1602 ..Default::default()
1603 });
1604 assert_eq!(
1605 languages.language_names(),
1606 &[
1607 "JSON".to_string(),
1608 "Plain Text".to_string(),
1609 "Rust".to_string(),
1610 ]
1611 );
1612
1613 let rust1 = languages.language_for_name("Rust");
1614 let rust2 = languages.language_for_name("Rust");
1615
1616 // Ensure language is still listed even if it's being loaded.
1617 assert_eq!(
1618 languages.language_names(),
1619 &[
1620 "JSON".to_string(),
1621 "Plain Text".to_string(),
1622 "Rust".to_string(),
1623 ]
1624 );
1625
1626 let (rust1, rust2) = futures::join!(rust1, rust2);
1627 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
1628
1629 // Ensure language is still listed even after loading it.
1630 assert_eq!(
1631 languages.language_names(),
1632 &[
1633 "JSON".to_string(),
1634 "Plain Text".to_string(),
1635 "Rust".to_string(),
1636 ]
1637 );
1638
1639 // Loading an unknown language returns an error.
1640 assert!(languages.language_for_name("Unknown").await.is_err());
1641 }
1642}