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