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 manifest;
15mod outline;
16pub mod proto;
17mod syntax_map;
18mod task_context;
19mod text_diff;
20mod toolchain;
21
22#[cfg(test)]
23pub mod buffer_tests;
24
25pub use crate::language_settings::EditPredictionsMode;
26use crate::language_settings::SoftWrap;
27use anyhow::{Context as _, Result, anyhow};
28use async_trait::async_trait;
29use collections::{HashMap, HashSet};
30use fs::Fs;
31use futures::Future;
32use gpui::{App, AsyncApp, Entity, SharedString, Task};
33pub use highlight_map::HighlightMap;
34use http_client::HttpClient;
35pub use language_registry::{LanguageName, LoadedLanguage};
36use lsp::{CodeActionKind, InitializeParams, LanguageServerBinary, LanguageServerBinaryOptions};
37pub use manifest::{ManifestName, ManifestProvider, ManifestQuery};
38use parking_lot::Mutex;
39use regex::Regex;
40use schemars::{
41 JsonSchema,
42 r#gen::SchemaGenerator,
43 schema::{InstanceType, Schema, SchemaObject},
44};
45use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
46use serde_json::Value;
47use settings::WorktreeId;
48use smol::future::FutureExt as _;
49use std::{
50 any::Any,
51 ffi::OsStr,
52 fmt::Debug,
53 hash::Hash,
54 mem,
55 ops::{DerefMut, Range},
56 path::{Path, PathBuf},
57 pin::Pin,
58 str,
59 sync::{
60 Arc, LazyLock,
61 atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst},
62 },
63};
64use std::{num::NonZeroU32, sync::OnceLock};
65use syntax_map::{QueryCursorHandle, SyntaxSnapshot};
66use task::RunnableTag;
67pub use task_context::{ContextProvider, RunnableRange};
68pub use text_diff::{DiffOptions, line_diff, text_diff, text_diff_with_options, unified_diff};
69use theme::SyntaxTheme;
70pub use toolchain::{LanguageToolchainStore, Toolchain, ToolchainList, ToolchainLister};
71use tree_sitter::{self, Query, QueryCursor, WasmStore, wasmtime};
72use util::serde::default_true;
73
74pub use buffer::Operation;
75pub use buffer::*;
76pub use diagnostic_set::{DiagnosticEntry, DiagnosticGroup};
77pub use language_registry::{
78 AvailableLanguage, BinaryStatus, LanguageNotFound, LanguageQueries, LanguageRegistry,
79 QUERY_FILENAME_PREFIXES,
80};
81pub use lsp::{LanguageServerId, LanguageServerName};
82pub use outline::*;
83pub use syntax_map::{OwnedSyntaxLayer, SyntaxLayer, ToTreeSitterPoint, TreeSitterOptions};
84pub use text::{AnchorRangeExt, LineEnding};
85pub use tree_sitter::{Node, Parser, Tree, TreeCursor};
86
87/// Initializes the `language` crate.
88///
89/// This should be called before making use of items from the create.
90pub fn init(cx: &mut App) {
91 language_settings::init(cx);
92}
93
94static QUERY_CURSORS: Mutex<Vec<QueryCursor>> = Mutex::new(vec![]);
95static PARSERS: Mutex<Vec<Parser>> = Mutex::new(vec![]);
96
97pub fn with_parser<F, R>(func: F) -> R
98where
99 F: FnOnce(&mut Parser) -> R,
100{
101 let mut parser = PARSERS.lock().pop().unwrap_or_else(|| {
102 let mut parser = Parser::new();
103 parser
104 .set_wasm_store(WasmStore::new(&WASM_ENGINE).unwrap())
105 .unwrap();
106 parser
107 });
108 parser.set_included_ranges(&[]).unwrap();
109 let result = func(&mut parser);
110 PARSERS.lock().push(parser);
111 result
112}
113
114pub fn with_query_cursor<F, R>(func: F) -> R
115where
116 F: FnOnce(&mut QueryCursor) -> R,
117{
118 let mut cursor = QueryCursorHandle::new();
119 func(cursor.deref_mut())
120}
121
122static NEXT_LANGUAGE_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
123static NEXT_GRAMMAR_ID: LazyLock<AtomicUsize> = LazyLock::new(Default::default);
124static WASM_ENGINE: LazyLock<wasmtime::Engine> = LazyLock::new(|| {
125 wasmtime::Engine::new(&wasmtime::Config::new()).expect("Failed to create Wasmtime engine")
126});
127
128/// A shared grammar for plain text, exposed for reuse by downstream crates.
129pub static PLAIN_TEXT: LazyLock<Arc<Language>> = LazyLock::new(|| {
130 Arc::new(Language::new(
131 LanguageConfig {
132 name: "Plain Text".into(),
133 soft_wrap: Some(SoftWrap::EditorWidth),
134 matcher: LanguageMatcher {
135 path_suffixes: vec!["txt".to_owned()],
136 first_line_pattern: None,
137 },
138 ..Default::default()
139 },
140 None,
141 ))
142});
143
144/// Types that represent a position in a buffer, and can be converted into
145/// an LSP position, to send to a language server.
146pub trait ToLspPosition {
147 /// Converts the value into an LSP position.
148 fn to_lsp_position(self) -> lsp::Position;
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Hash)]
152pub struct Location {
153 pub buffer: Entity<Buffer>,
154 pub range: Range<Anchor>,
155}
156
157/// Represents a Language Server, with certain cached sync properties.
158/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
159/// once at startup, and caches the results.
160pub struct CachedLspAdapter {
161 pub name: LanguageServerName,
162 pub disk_based_diagnostic_sources: Vec<String>,
163 pub disk_based_diagnostics_progress_token: Option<String>,
164 language_ids: HashMap<String, String>,
165 pub adapter: Arc<dyn LspAdapter>,
166 pub reinstall_attempt_count: AtomicU64,
167 cached_binary: futures::lock::Mutex<Option<LanguageServerBinary>>,
168 manifest_name: OnceLock<Option<ManifestName>>,
169 attach_kind: OnceLock<Attach>,
170}
171
172impl Debug for CachedLspAdapter {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 f.debug_struct("CachedLspAdapter")
175 .field("name", &self.name)
176 .field(
177 "disk_based_diagnostic_sources",
178 &self.disk_based_diagnostic_sources,
179 )
180 .field(
181 "disk_based_diagnostics_progress_token",
182 &self.disk_based_diagnostics_progress_token,
183 )
184 .field("language_ids", &self.language_ids)
185 .field("reinstall_attempt_count", &self.reinstall_attempt_count)
186 .finish_non_exhaustive()
187 }
188}
189
190impl CachedLspAdapter {
191 pub fn new(adapter: Arc<dyn LspAdapter>) -> Arc<Self> {
192 let name = adapter.name();
193 let disk_based_diagnostic_sources = adapter.disk_based_diagnostic_sources();
194 let disk_based_diagnostics_progress_token = adapter.disk_based_diagnostics_progress_token();
195 let language_ids = adapter.language_ids();
196
197 Arc::new(CachedLspAdapter {
198 name,
199 disk_based_diagnostic_sources,
200 disk_based_diagnostics_progress_token,
201 language_ids,
202 adapter,
203 cached_binary: Default::default(),
204 reinstall_attempt_count: AtomicU64::new(0),
205 attach_kind: Default::default(),
206 manifest_name: Default::default(),
207 })
208 }
209
210 pub fn name(&self) -> LanguageServerName {
211 self.adapter.name().clone()
212 }
213
214 pub async fn get_language_server_command(
215 self: Arc<Self>,
216 delegate: Arc<dyn LspAdapterDelegate>,
217 toolchains: Arc<dyn LanguageToolchainStore>,
218 binary_options: LanguageServerBinaryOptions,
219 cx: &mut AsyncApp,
220 ) -> Result<LanguageServerBinary> {
221 let cached_binary = self.cached_binary.lock().await;
222 self.adapter
223 .clone()
224 .get_language_server_command(delegate, toolchains, binary_options, cached_binary, cx)
225 .await
226 }
227
228 pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
229 self.adapter.code_action_kinds()
230 }
231
232 pub fn process_diagnostics(
233 &self,
234 params: &mut lsp::PublishDiagnosticsParams,
235 server_id: LanguageServerId,
236 existing_diagnostics: Option<&'_ Buffer>,
237 ) {
238 self.adapter
239 .process_diagnostics(params, server_id, existing_diagnostics)
240 }
241
242 pub async fn process_completions(&self, completion_items: &mut [lsp::CompletionItem]) {
243 self.adapter.process_completions(completion_items).await
244 }
245
246 pub async fn labels_for_completions(
247 &self,
248 completion_items: &[lsp::CompletionItem],
249 language: &Arc<Language>,
250 ) -> Result<Vec<Option<CodeLabel>>> {
251 self.adapter
252 .clone()
253 .labels_for_completions(completion_items, language)
254 .await
255 }
256
257 pub async fn labels_for_symbols(
258 &self,
259 symbols: &[(String, lsp::SymbolKind)],
260 language: &Arc<Language>,
261 ) -> Result<Vec<Option<CodeLabel>>> {
262 self.adapter
263 .clone()
264 .labels_for_symbols(symbols, language)
265 .await
266 }
267
268 pub fn language_id(&self, language_name: &LanguageName) -> String {
269 self.language_ids
270 .get(language_name.as_ref())
271 .cloned()
272 .unwrap_or_else(|| language_name.lsp_id())
273 }
274 pub fn manifest_name(&self) -> Option<ManifestName> {
275 self.manifest_name
276 .get_or_init(|| self.adapter.manifest_name())
277 .clone()
278 }
279 pub fn attach_kind(&self) -> Attach {
280 *self.attach_kind.get_or_init(|| self.adapter.attach_kind())
281 }
282}
283
284#[derive(Clone, Copy, Debug, PartialEq)]
285pub enum Attach {
286 /// Create a single language server instance per subproject root.
287 InstancePerRoot,
288 /// Use one shared language server instance for all subprojects within a project.
289 Shared,
290}
291
292impl Attach {
293 pub fn root_path(
294 &self,
295 root_subproject_path: (WorktreeId, Arc<Path>),
296 ) -> (WorktreeId, Arc<Path>) {
297 match self {
298 Attach::InstancePerRoot => root_subproject_path,
299 Attach::Shared => (root_subproject_path.0, Arc::from(Path::new(""))),
300 }
301 }
302}
303
304/// [`LspAdapterDelegate`] allows [`LspAdapter]` implementations to interface with the application
305// e.g. to display a notification or fetch data from the web.
306#[async_trait]
307pub trait LspAdapterDelegate: Send + Sync {
308 fn show_notification(&self, message: &str, cx: &mut App);
309 fn http_client(&self) -> Arc<dyn HttpClient>;
310 fn worktree_id(&self) -> WorktreeId;
311 fn worktree_root_path(&self) -> &Path;
312 fn exists(&self, path: &Path, is_dir: Option<bool>) -> bool;
313 fn update_status(&self, language: LanguageServerName, status: BinaryStatus);
314 fn registered_lsp_adapters(&self) -> Vec<Arc<dyn LspAdapter>>;
315 async fn language_server_download_dir(&self, name: &LanguageServerName) -> Option<Arc<Path>>;
316
317 async fn npm_package_installed_version(
318 &self,
319 package_name: &str,
320 ) -> Result<Option<(PathBuf, String)>>;
321 async fn which(&self, command: &OsStr) -> Option<PathBuf>;
322 async fn shell_env(&self) -> HashMap<String, String>;
323 async fn read_text_file(&self, path: PathBuf) -> Result<String>;
324 async fn try_exec(&self, binary: LanguageServerBinary) -> Result<()>;
325}
326
327#[async_trait(?Send)]
328pub trait LspAdapter: 'static + Send + Sync {
329 fn name(&self) -> LanguageServerName;
330
331 fn get_language_server_command<'a>(
332 self: Arc<Self>,
333 delegate: Arc<dyn LspAdapterDelegate>,
334 toolchains: Arc<dyn LanguageToolchainStore>,
335 binary_options: LanguageServerBinaryOptions,
336 mut cached_binary: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
337 cx: &'a mut AsyncApp,
338 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
339 async move {
340 // First we check whether the adapter can give us a user-installed binary.
341 // If so, we do *not* want to cache that, because each worktree might give us a different
342 // binary:
343 //
344 // worktree 1: user-installed at `.bin/gopls`
345 // worktree 2: user-installed at `~/bin/gopls`
346 // worktree 3: no gopls found in PATH -> fallback to Zed installation
347 //
348 // We only want to cache when we fall back to the global one,
349 // because we don't want to download and overwrite our global one
350 // for each worktree we might have open.
351 if binary_options.allow_path_lookup {
352 if let Some(binary) = self.check_if_user_installed(delegate.as_ref(), toolchains, cx).await {
353 log::info!(
354 "found user-installed language server for {}. path: {:?}, arguments: {:?}",
355 self.name().0,
356 binary.path,
357 binary.arguments
358 );
359 return Ok(binary);
360 }
361 }
362
363 if !binary_options.allow_binary_download {
364 return Err(anyhow!("downloading language servers disabled"));
365 }
366
367 if let Some(cached_binary) = cached_binary.as_ref() {
368 return Ok(cached_binary.clone());
369 }
370
371 let Some(container_dir) = delegate.language_server_download_dir(&self.name()).await else {
372 anyhow::bail!("no language server download dir defined")
373 };
374
375 let mut binary = try_fetch_server_binary(self.as_ref(), &delegate, container_dir.to_path_buf(), cx).await;
376
377 if let Err(error) = binary.as_ref() {
378 if let Some(prev_downloaded_binary) = self
379 .cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
380 .await
381 {
382 log::info!(
383 "failed to fetch newest version of language server {:?}. error: {:?}, falling back to using {:?}",
384 self.name(),
385 error,
386 prev_downloaded_binary.path
387 );
388 binary = Ok(prev_downloaded_binary);
389 } else {
390 delegate.update_status(
391 self.name(),
392 BinaryStatus::Failed {
393 error: format!("{error:?}"),
394 },
395 );
396 }
397 }
398
399 if let Ok(binary) = &binary {
400 *cached_binary = Some(binary.clone());
401 }
402
403 binary
404 }
405 .boxed_local()
406 }
407
408 async fn check_if_user_installed(
409 &self,
410 _: &dyn LspAdapterDelegate,
411 _: Arc<dyn LanguageToolchainStore>,
412 _: &AsyncApp,
413 ) -> Option<LanguageServerBinary> {
414 None
415 }
416
417 async fn fetch_latest_server_version(
418 &self,
419 delegate: &dyn LspAdapterDelegate,
420 ) -> Result<Box<dyn 'static + Send + Any>>;
421
422 fn will_fetch_server(
423 &self,
424 _: &Arc<dyn LspAdapterDelegate>,
425 _: &mut AsyncApp,
426 ) -> Option<Task<Result<()>>> {
427 None
428 }
429
430 async fn check_if_version_installed(
431 &self,
432 _version: &(dyn 'static + Send + Any),
433 _container_dir: &PathBuf,
434 _delegate: &dyn LspAdapterDelegate,
435 ) -> Option<LanguageServerBinary> {
436 None
437 }
438
439 async fn fetch_server_binary(
440 &self,
441 latest_version: Box<dyn 'static + Send + Any>,
442 container_dir: PathBuf,
443 delegate: &dyn LspAdapterDelegate,
444 ) -> Result<LanguageServerBinary>;
445
446 async fn cached_server_binary(
447 &self,
448 container_dir: PathBuf,
449 delegate: &dyn LspAdapterDelegate,
450 ) -> Option<LanguageServerBinary>;
451
452 fn process_diagnostics(
453 &self,
454 _: &mut lsp::PublishDiagnosticsParams,
455 _: LanguageServerId,
456 _: Option<&'_ Buffer>,
457 ) {
458 }
459
460 /// Post-processes completions provided by the language server.
461 async fn process_completions(&self, _: &mut [lsp::CompletionItem]) {}
462
463 async fn labels_for_completions(
464 self: Arc<Self>,
465 completions: &[lsp::CompletionItem],
466 language: &Arc<Language>,
467 ) -> Result<Vec<Option<CodeLabel>>> {
468 let mut labels = Vec::new();
469 for (ix, completion) in completions.iter().enumerate() {
470 let label = self.label_for_completion(completion, language).await;
471 if let Some(label) = label {
472 labels.resize(ix + 1, None);
473 *labels.last_mut().unwrap() = Some(label);
474 }
475 }
476 Ok(labels)
477 }
478
479 async fn label_for_completion(
480 &self,
481 _: &lsp::CompletionItem,
482 _: &Arc<Language>,
483 ) -> Option<CodeLabel> {
484 None
485 }
486
487 async fn labels_for_symbols(
488 self: Arc<Self>,
489 symbols: &[(String, lsp::SymbolKind)],
490 language: &Arc<Language>,
491 ) -> Result<Vec<Option<CodeLabel>>> {
492 let mut labels = Vec::new();
493 for (ix, (name, kind)) in symbols.iter().enumerate() {
494 let label = self.label_for_symbol(name, *kind, language).await;
495 if let Some(label) = label {
496 labels.resize(ix + 1, None);
497 *labels.last_mut().unwrap() = Some(label);
498 }
499 }
500 Ok(labels)
501 }
502
503 async fn label_for_symbol(
504 &self,
505 _: &str,
506 _: lsp::SymbolKind,
507 _: &Arc<Language>,
508 ) -> Option<CodeLabel> {
509 None
510 }
511
512 /// Returns initialization options that are going to be sent to a LSP server as a part of [`lsp::InitializeParams`]
513 async fn initialization_options(
514 self: Arc<Self>,
515 _: &dyn Fs,
516 _: &Arc<dyn LspAdapterDelegate>,
517 ) -> Result<Option<Value>> {
518 Ok(None)
519 }
520
521 async fn workspace_configuration(
522 self: Arc<Self>,
523 _: &dyn Fs,
524 _: &Arc<dyn LspAdapterDelegate>,
525 _: Arc<dyn LanguageToolchainStore>,
526 _cx: &mut AsyncApp,
527 ) -> Result<Value> {
528 Ok(serde_json::json!({}))
529 }
530
531 async fn additional_initialization_options(
532 self: Arc<Self>,
533 _target_language_server_id: LanguageServerName,
534 _: &dyn Fs,
535 _: &Arc<dyn LspAdapterDelegate>,
536 ) -> Result<Option<Value>> {
537 Ok(None)
538 }
539
540 async fn additional_workspace_configuration(
541 self: Arc<Self>,
542 _target_language_server_id: LanguageServerName,
543 _: &dyn Fs,
544 _: &Arc<dyn LspAdapterDelegate>,
545 _: Arc<dyn LanguageToolchainStore>,
546 _cx: &mut AsyncApp,
547 ) -> Result<Option<Value>> {
548 Ok(None)
549 }
550
551 /// Returns a list of code actions supported by a given LspAdapter
552 fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
553 Some(vec![
554 CodeActionKind::EMPTY,
555 CodeActionKind::QUICKFIX,
556 CodeActionKind::REFACTOR,
557 CodeActionKind::REFACTOR_EXTRACT,
558 CodeActionKind::SOURCE,
559 ])
560 }
561
562 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
563 Default::default()
564 }
565
566 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
567 None
568 }
569
570 fn language_ids(&self) -> HashMap<String, String> {
571 Default::default()
572 }
573
574 /// Support custom initialize params.
575 fn prepare_initialize_params(&self, original: InitializeParams) -> Result<InitializeParams> {
576 Ok(original)
577 }
578
579 fn attach_kind(&self) -> Attach {
580 Attach::Shared
581 }
582
583 fn manifest_name(&self) -> Option<ManifestName> {
584 None
585 }
586
587 /// Method only implemented by the default JSON language server adapter.
588 /// Used to provide dynamic reloading of the JSON schemas used to
589 /// provide autocompletion and diagnostics in Zed setting and keybind
590 /// files
591 fn is_primary_zed_json_schema_adapter(&self) -> bool {
592 false
593 }
594
595 /// Method only implemented by the default JSON language server adapter.
596 /// Used to clear the cache of JSON schemas that are used to provide
597 /// autocompletion and diagnostics in Zed settings and keybinds files.
598 /// Should not be called unless the callee is sure that
599 /// `Self::is_primary_zed_json_schema_adapter` returns `true`
600 async fn clear_zed_json_schema_cache(&self) {
601 unreachable!(
602 "Not implemented for this adapter. This method should only be called on the default JSON language server adapter"
603 );
604 }
605}
606
607async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
608 adapter: &L,
609 delegate: &Arc<dyn LspAdapterDelegate>,
610 container_dir: PathBuf,
611 cx: &mut AsyncApp,
612) -> Result<LanguageServerBinary> {
613 if let Some(task) = adapter.will_fetch_server(delegate, cx) {
614 task.await?;
615 }
616
617 let name = adapter.name();
618 log::info!("fetching latest version of language server {:?}", name.0);
619 delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
620
621 let latest_version = adapter
622 .fetch_latest_server_version(delegate.as_ref())
623 .await?;
624
625 if let Some(binary) = adapter
626 .check_if_version_installed(latest_version.as_ref(), &container_dir, delegate.as_ref())
627 .await
628 {
629 log::info!("language server {:?} is already installed", name.0);
630 delegate.update_status(name.clone(), BinaryStatus::None);
631 Ok(binary)
632 } else {
633 log::info!("downloading language server {:?}", name.0);
634 delegate.update_status(adapter.name(), BinaryStatus::Downloading);
635 let binary = adapter
636 .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
637 .await;
638
639 delegate.update_status(name.clone(), BinaryStatus::None);
640 binary
641 }
642}
643
644#[derive(Clone, Debug, Default, PartialEq, Eq)]
645pub struct CodeLabel {
646 /// The text to display.
647 pub text: String,
648 /// Syntax highlighting runs.
649 pub runs: Vec<(Range<usize>, HighlightId)>,
650 /// The portion of the text that should be used in fuzzy filtering.
651 pub filter_range: Range<usize>,
652}
653
654#[derive(Clone, Deserialize, JsonSchema)]
655pub struct LanguageConfig {
656 /// Human-readable name of the language.
657 pub name: LanguageName,
658 /// The name of this language for a Markdown code fence block
659 pub code_fence_block_name: Option<Arc<str>>,
660 // The name of the grammar in a WASM bundle (experimental).
661 pub grammar: Option<Arc<str>>,
662 /// The criteria for matching this language to a given file.
663 #[serde(flatten)]
664 pub matcher: LanguageMatcher,
665 /// List of bracket types in a language.
666 #[serde(default)]
667 #[schemars(schema_with = "bracket_pair_config_json_schema")]
668 pub brackets: BracketPairConfig,
669 /// If set to true, auto indentation uses last non empty line to determine
670 /// the indentation level for a new line.
671 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
672 pub auto_indent_using_last_non_empty_line: bool,
673 // Whether indentation of pasted content should be adjusted based on the context.
674 #[serde(default)]
675 pub auto_indent_on_paste: Option<bool>,
676 /// A regex that is used to determine whether the indentation level should be
677 /// increased in the following line.
678 #[serde(default, deserialize_with = "deserialize_regex")]
679 #[schemars(schema_with = "regex_json_schema")]
680 pub increase_indent_pattern: Option<Regex>,
681 /// A regex that is used to determine whether the indentation level should be
682 /// decreased in the following line.
683 #[serde(default, deserialize_with = "deserialize_regex")]
684 #[schemars(schema_with = "regex_json_schema")]
685 pub decrease_indent_pattern: Option<Regex>,
686 /// A list of characters that trigger the automatic insertion of a closing
687 /// bracket when they immediately precede the point where an opening
688 /// bracket is inserted.
689 #[serde(default)]
690 pub autoclose_before: String,
691 /// A placeholder used internally by Semantic Index.
692 #[serde(default)]
693 pub collapsed_placeholder: String,
694 /// A line comment string that is inserted in e.g. `toggle comments` action.
695 /// A language can have multiple flavours of line comments. All of the provided line comments are
696 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
697 #[serde(default)]
698 pub line_comments: Vec<Arc<str>>,
699 /// Starting and closing characters of a block comment.
700 #[serde(default)]
701 pub block_comment: Option<(Arc<str>, Arc<str>)>,
702 /// A list of language servers that are allowed to run on subranges of a given language.
703 #[serde(default)]
704 pub scope_opt_in_language_servers: Vec<LanguageServerName>,
705 #[serde(default)]
706 pub overrides: HashMap<String, LanguageConfigOverride>,
707 /// A list of characters that Zed should treat as word characters for the
708 /// purpose of features that operate on word boundaries, like 'move to next word end'
709 /// or a whole-word search in buffer search.
710 #[serde(default)]
711 pub word_characters: HashSet<char>,
712 /// Whether to indent lines using tab characters, as opposed to multiple
713 /// spaces.
714 #[serde(default)]
715 pub hard_tabs: Option<bool>,
716 /// How many columns a tab should occupy.
717 #[serde(default)]
718 pub tab_size: Option<NonZeroU32>,
719 /// How to soft-wrap long lines of text.
720 #[serde(default)]
721 pub soft_wrap: Option<SoftWrap>,
722 /// The name of a Prettier parser that will be used for this language when no file path is available.
723 /// If there's a parser name in the language settings, that will be used instead.
724 #[serde(default)]
725 pub prettier_parser_name: Option<String>,
726 /// If true, this language is only for syntax highlighting via an injection into other
727 /// languages, but should not appear to the user as a distinct language.
728 #[serde(default)]
729 pub hidden: bool,
730 /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
731 #[serde(default)]
732 pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
733 /// A list of characters that Zed should treat as word characters for completion queries.
734 #[serde(default)]
735 pub completion_query_characters: HashSet<char>,
736}
737
738#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
739pub struct LanguageMatcher {
740 /// 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`.
741 #[serde(default)]
742 pub path_suffixes: Vec<String>,
743 /// A regex pattern that determines whether the language should be assigned to a file or not.
744 #[serde(
745 default,
746 serialize_with = "serialize_regex",
747 deserialize_with = "deserialize_regex"
748 )]
749 #[schemars(schema_with = "regex_json_schema")]
750 pub first_line_pattern: Option<Regex>,
751}
752
753/// The configuration for JSX tag auto-closing.
754#[derive(Clone, Deserialize, JsonSchema)]
755pub struct JsxTagAutoCloseConfig {
756 /// The name of the node for a opening tag
757 pub open_tag_node_name: String,
758 /// The name of the node for an closing tag
759 pub close_tag_node_name: String,
760 /// The name of the node for a complete element with children for open and close tags
761 pub jsx_element_node_name: String,
762 /// The name of the node found within both opening and closing
763 /// tags that describes the tag name
764 pub tag_name_node_name: String,
765 /// Alternate Node names for tag names.
766 /// Specifically needed as TSX represents the name in `<Foo.Bar>`
767 /// as `member_expression` rather than `identifier` as usual
768 #[serde(default)]
769 pub tag_name_node_name_alternates: Vec<String>,
770 /// Some grammars are smart enough to detect a closing tag
771 /// that is not valid i.e. doesn't match it's corresponding
772 /// opening tag or does not have a corresponding opening tag
773 /// This should be set to the name of the node for invalid
774 /// closing tags if the grammar contains such a node, otherwise
775 /// detecting already closed tags will not work properly
776 #[serde(default)]
777 pub erroneous_close_tag_node_name: Option<String>,
778 /// See above for erroneous_close_tag_node_name for details
779 /// This should be set if the node used for the tag name
780 /// within erroneous closing tags is different from the
781 /// normal tag name node name
782 #[serde(default)]
783 pub erroneous_close_tag_name_node_name: Option<String>,
784}
785
786/// Represents a language for the given range. Some languages (e.g. HTML)
787/// interleave several languages together, thus a single buffer might actually contain
788/// several nested scopes.
789#[derive(Clone, Debug)]
790pub struct LanguageScope {
791 language: Arc<Language>,
792 override_id: Option<u32>,
793}
794
795#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
796pub struct LanguageConfigOverride {
797 #[serde(default)]
798 pub line_comments: Override<Vec<Arc<str>>>,
799 #[serde(default)]
800 pub block_comment: Override<(Arc<str>, Arc<str>)>,
801 #[serde(skip)]
802 pub disabled_bracket_ixs: Vec<u16>,
803 #[serde(default)]
804 pub word_characters: Override<HashSet<char>>,
805 #[serde(default)]
806 pub completion_query_characters: Override<HashSet<char>>,
807 #[serde(default)]
808 pub opt_into_language_servers: Vec<LanguageServerName>,
809}
810
811#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
812#[serde(untagged)]
813pub enum Override<T> {
814 Remove { remove: bool },
815 Set(T),
816}
817
818impl<T> Default for Override<T> {
819 fn default() -> Self {
820 Override::Remove { remove: false }
821 }
822}
823
824impl<T> Override<T> {
825 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
826 match this {
827 Some(Self::Set(value)) => Some(value),
828 Some(Self::Remove { remove: true }) => None,
829 Some(Self::Remove { remove: false }) | None => original,
830 }
831 }
832}
833
834impl Default for LanguageConfig {
835 fn default() -> Self {
836 Self {
837 name: LanguageName::new(""),
838 code_fence_block_name: None,
839 grammar: None,
840 matcher: LanguageMatcher::default(),
841 brackets: Default::default(),
842 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
843 auto_indent_on_paste: None,
844 increase_indent_pattern: Default::default(),
845 decrease_indent_pattern: Default::default(),
846 autoclose_before: Default::default(),
847 line_comments: Default::default(),
848 block_comment: Default::default(),
849 scope_opt_in_language_servers: Default::default(),
850 overrides: Default::default(),
851 word_characters: Default::default(),
852 collapsed_placeholder: Default::default(),
853 hard_tabs: None,
854 tab_size: None,
855 soft_wrap: None,
856 prettier_parser_name: None,
857 hidden: false,
858 jsx_tag_auto_close: None,
859 completion_query_characters: Default::default(),
860 }
861 }
862}
863
864fn auto_indent_using_last_non_empty_line_default() -> bool {
865 true
866}
867
868fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
869 let source = Option::<String>::deserialize(d)?;
870 if let Some(source) = source {
871 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
872 } else {
873 Ok(None)
874 }
875}
876
877fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
878 Schema::Object(SchemaObject {
879 instance_type: Some(InstanceType::String.into()),
880 ..Default::default()
881 })
882}
883
884fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
885where
886 S: Serializer,
887{
888 match regex {
889 Some(regex) => serializer.serialize_str(regex.as_str()),
890 None => serializer.serialize_none(),
891 }
892}
893
894#[doc(hidden)]
895#[cfg(any(test, feature = "test-support"))]
896pub struct FakeLspAdapter {
897 pub name: &'static str,
898 pub initialization_options: Option<Value>,
899 pub prettier_plugins: Vec<&'static str>,
900 pub disk_based_diagnostics_progress_token: Option<String>,
901 pub disk_based_diagnostics_sources: Vec<String>,
902 pub language_server_binary: LanguageServerBinary,
903
904 pub capabilities: lsp::ServerCapabilities,
905 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
906 pub label_for_completion: Option<
907 Box<
908 dyn 'static
909 + Send
910 + Sync
911 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
912 >,
913 >,
914}
915
916/// Configuration of handling bracket pairs for a given language.
917///
918/// This struct includes settings for defining which pairs of characters are considered brackets and
919/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
920#[derive(Clone, Debug, Default, JsonSchema)]
921pub struct BracketPairConfig {
922 /// A list of character pairs that should be treated as brackets in the context of a given language.
923 pub pairs: Vec<BracketPair>,
924 /// A list of tree-sitter scopes for which a given bracket should not be active.
925 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
926 #[serde(skip)]
927 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
928}
929
930impl BracketPairConfig {
931 pub fn is_closing_brace(&self, c: char) -> bool {
932 self.pairs.iter().any(|pair| pair.end.starts_with(c))
933 }
934}
935
936fn bracket_pair_config_json_schema(r#gen: &mut SchemaGenerator) -> Schema {
937 Option::<Vec<BracketPairContent>>::json_schema(r#gen)
938}
939
940#[derive(Deserialize, JsonSchema)]
941pub struct BracketPairContent {
942 #[serde(flatten)]
943 pub bracket_pair: BracketPair,
944 #[serde(default)]
945 pub not_in: Vec<String>,
946}
947
948impl<'de> Deserialize<'de> for BracketPairConfig {
949 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
950 where
951 D: Deserializer<'de>,
952 {
953 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
954 let mut brackets = Vec::with_capacity(result.len());
955 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
956 for entry in result {
957 brackets.push(entry.bracket_pair);
958 disabled_scopes_by_bracket_ix.push(entry.not_in);
959 }
960
961 Ok(BracketPairConfig {
962 pairs: brackets,
963 disabled_scopes_by_bracket_ix,
964 })
965 }
966}
967
968/// Describes a single bracket pair and how an editor should react to e.g. inserting
969/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
970#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
971pub struct BracketPair {
972 /// Starting substring for a bracket.
973 pub start: String,
974 /// Ending substring for a bracket.
975 pub end: String,
976 /// True if `end` should be automatically inserted right after `start` characters.
977 pub close: bool,
978 /// True if selected text should be surrounded by `start` and `end` characters.
979 #[serde(default = "default_true")]
980 pub surround: bool,
981 /// True if an extra newline should be inserted while the cursor is in the middle
982 /// of that bracket pair.
983 pub newline: bool,
984}
985
986#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
987pub struct LanguageId(usize);
988
989impl LanguageId {
990 pub(crate) fn new() -> Self {
991 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
992 }
993}
994
995pub struct Language {
996 pub(crate) id: LanguageId,
997 pub(crate) config: LanguageConfig,
998 pub(crate) grammar: Option<Arc<Grammar>>,
999 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
1000 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
1001}
1002
1003#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1004pub struct GrammarId(pub usize);
1005
1006impl GrammarId {
1007 pub(crate) fn new() -> Self {
1008 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1009 }
1010}
1011
1012pub struct Grammar {
1013 id: GrammarId,
1014 pub ts_language: tree_sitter::Language,
1015 pub(crate) error_query: Option<Query>,
1016 pub(crate) highlights_query: Option<Query>,
1017 pub(crate) brackets_config: Option<BracketsConfig>,
1018 pub(crate) redactions_config: Option<RedactionConfig>,
1019 pub(crate) runnable_config: Option<RunnableConfig>,
1020 pub(crate) indents_config: Option<IndentConfig>,
1021 pub outline_config: Option<OutlineConfig>,
1022 pub text_object_config: Option<TextObjectConfig>,
1023 pub embedding_config: Option<EmbeddingConfig>,
1024 pub(crate) injection_config: Option<InjectionConfig>,
1025 pub(crate) override_config: Option<OverrideConfig>,
1026 pub(crate) highlight_map: Mutex<HighlightMap>,
1027}
1028
1029struct IndentConfig {
1030 query: Query,
1031 indent_capture_ix: u32,
1032 start_capture_ix: Option<u32>,
1033 end_capture_ix: Option<u32>,
1034 outdent_capture_ix: Option<u32>,
1035}
1036
1037pub struct OutlineConfig {
1038 pub query: Query,
1039 pub item_capture_ix: u32,
1040 pub name_capture_ix: u32,
1041 pub context_capture_ix: Option<u32>,
1042 pub extra_context_capture_ix: Option<u32>,
1043 pub open_capture_ix: Option<u32>,
1044 pub close_capture_ix: Option<u32>,
1045 pub annotation_capture_ix: Option<u32>,
1046}
1047
1048#[derive(Debug, Clone, Copy, PartialEq)]
1049pub enum TextObject {
1050 InsideFunction,
1051 AroundFunction,
1052 InsideClass,
1053 AroundClass,
1054 InsideComment,
1055 AroundComment,
1056}
1057
1058impl TextObject {
1059 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1060 match name {
1061 "function.inside" => Some(TextObject::InsideFunction),
1062 "function.around" => Some(TextObject::AroundFunction),
1063 "class.inside" => Some(TextObject::InsideClass),
1064 "class.around" => Some(TextObject::AroundClass),
1065 "comment.inside" => Some(TextObject::InsideComment),
1066 "comment.around" => Some(TextObject::AroundComment),
1067 _ => None,
1068 }
1069 }
1070
1071 pub fn around(&self) -> Option<Self> {
1072 match self {
1073 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1074 TextObject::InsideClass => Some(TextObject::AroundClass),
1075 TextObject::InsideComment => Some(TextObject::AroundComment),
1076 _ => None,
1077 }
1078 }
1079}
1080
1081pub struct TextObjectConfig {
1082 pub query: Query,
1083 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1084}
1085
1086#[derive(Debug)]
1087pub struct EmbeddingConfig {
1088 pub query: Query,
1089 pub item_capture_ix: u32,
1090 pub name_capture_ix: Option<u32>,
1091 pub context_capture_ix: Option<u32>,
1092 pub collapse_capture_ix: Option<u32>,
1093 pub keep_capture_ix: Option<u32>,
1094}
1095
1096struct InjectionConfig {
1097 query: Query,
1098 content_capture_ix: u32,
1099 language_capture_ix: Option<u32>,
1100 patterns: Vec<InjectionPatternConfig>,
1101}
1102
1103struct RedactionConfig {
1104 pub query: Query,
1105 pub redaction_capture_ix: u32,
1106}
1107
1108#[derive(Clone, Debug, PartialEq)]
1109enum RunnableCapture {
1110 Named(SharedString),
1111 Run,
1112}
1113
1114struct RunnableConfig {
1115 pub query: Query,
1116 /// A mapping from capture indice to capture kind
1117 pub extra_captures: Vec<RunnableCapture>,
1118}
1119
1120struct OverrideConfig {
1121 query: Query,
1122 values: HashMap<u32, OverrideEntry>,
1123}
1124
1125#[derive(Debug)]
1126struct OverrideEntry {
1127 name: String,
1128 range_is_inclusive: bool,
1129 value: LanguageConfigOverride,
1130}
1131
1132#[derive(Default, Clone)]
1133struct InjectionPatternConfig {
1134 language: Option<Box<str>>,
1135 combined: bool,
1136}
1137
1138struct BracketsConfig {
1139 query: Query,
1140 open_capture_ix: u32,
1141 close_capture_ix: u32,
1142 patterns: Vec<BracketsPatternConfig>,
1143}
1144
1145#[derive(Clone, Debug, Default)]
1146struct BracketsPatternConfig {
1147 newline_only: bool,
1148}
1149
1150impl Language {
1151 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1152 Self::new_with_id(LanguageId::new(), config, ts_language)
1153 }
1154
1155 pub fn id(&self) -> LanguageId {
1156 self.id
1157 }
1158
1159 fn new_with_id(
1160 id: LanguageId,
1161 config: LanguageConfig,
1162 ts_language: Option<tree_sitter::Language>,
1163 ) -> Self {
1164 Self {
1165 id,
1166 config,
1167 grammar: ts_language.map(|ts_language| {
1168 Arc::new(Grammar {
1169 id: GrammarId::new(),
1170 highlights_query: None,
1171 brackets_config: None,
1172 outline_config: None,
1173 text_object_config: None,
1174 embedding_config: None,
1175 indents_config: None,
1176 injection_config: None,
1177 override_config: None,
1178 redactions_config: None,
1179 runnable_config: None,
1180 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1181 ts_language,
1182 highlight_map: Default::default(),
1183 })
1184 }),
1185 context_provider: None,
1186 toolchain: None,
1187 }
1188 }
1189
1190 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1191 self.context_provider = provider;
1192 self
1193 }
1194
1195 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1196 self.toolchain = provider;
1197 self
1198 }
1199
1200 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1201 if let Some(query) = queries.highlights {
1202 self = self
1203 .with_highlights_query(query.as_ref())
1204 .context("Error loading highlights query")?;
1205 }
1206 if let Some(query) = queries.brackets {
1207 self = self
1208 .with_brackets_query(query.as_ref())
1209 .context("Error loading brackets query")?;
1210 }
1211 if let Some(query) = queries.indents {
1212 self = self
1213 .with_indents_query(query.as_ref())
1214 .context("Error loading indents query")?;
1215 }
1216 if let Some(query) = queries.outline {
1217 self = self
1218 .with_outline_query(query.as_ref())
1219 .context("Error loading outline query")?;
1220 }
1221 if let Some(query) = queries.embedding {
1222 self = self
1223 .with_embedding_query(query.as_ref())
1224 .context("Error loading embedding query")?;
1225 }
1226 if let Some(query) = queries.injections {
1227 self = self
1228 .with_injection_query(query.as_ref())
1229 .context("Error loading injection query")?;
1230 }
1231 if let Some(query) = queries.overrides {
1232 self = self
1233 .with_override_query(query.as_ref())
1234 .context("Error loading override query")?;
1235 }
1236 if let Some(query) = queries.redactions {
1237 self = self
1238 .with_redaction_query(query.as_ref())
1239 .context("Error loading redaction query")?;
1240 }
1241 if let Some(query) = queries.runnables {
1242 self = self
1243 .with_runnable_query(query.as_ref())
1244 .context("Error loading runnables query")?;
1245 }
1246 if let Some(query) = queries.text_objects {
1247 self = self
1248 .with_text_object_query(query.as_ref())
1249 .context("Error loading textobject query")?;
1250 }
1251 Ok(self)
1252 }
1253
1254 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1255 let grammar = self
1256 .grammar_mut()
1257 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1258 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1259 Ok(self)
1260 }
1261
1262 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1263 let grammar = self
1264 .grammar_mut()
1265 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1266
1267 let query = Query::new(&grammar.ts_language, source)?;
1268 let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1269
1270 for name in query.capture_names().iter() {
1271 let kind = if *name == "run" {
1272 RunnableCapture::Run
1273 } else {
1274 RunnableCapture::Named(name.to_string().into())
1275 };
1276 extra_captures.push(kind);
1277 }
1278
1279 grammar.runnable_config = Some(RunnableConfig {
1280 extra_captures,
1281 query,
1282 });
1283
1284 Ok(self)
1285 }
1286
1287 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1288 let grammar = self
1289 .grammar_mut()
1290 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1291 let query = Query::new(&grammar.ts_language, source)?;
1292 let mut item_capture_ix = None;
1293 let mut name_capture_ix = None;
1294 let mut context_capture_ix = None;
1295 let mut extra_context_capture_ix = None;
1296 let mut open_capture_ix = None;
1297 let mut close_capture_ix = None;
1298 let mut annotation_capture_ix = None;
1299 get_capture_indices(
1300 &query,
1301 &mut [
1302 ("item", &mut item_capture_ix),
1303 ("name", &mut name_capture_ix),
1304 ("context", &mut context_capture_ix),
1305 ("context.extra", &mut extra_context_capture_ix),
1306 ("open", &mut open_capture_ix),
1307 ("close", &mut close_capture_ix),
1308 ("annotation", &mut annotation_capture_ix),
1309 ],
1310 );
1311 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1312 grammar.outline_config = Some(OutlineConfig {
1313 query,
1314 item_capture_ix,
1315 name_capture_ix,
1316 context_capture_ix,
1317 extra_context_capture_ix,
1318 open_capture_ix,
1319 close_capture_ix,
1320 annotation_capture_ix,
1321 });
1322 }
1323 Ok(self)
1324 }
1325
1326 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1327 let grammar = self
1328 .grammar_mut()
1329 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1330 let query = Query::new(&grammar.ts_language, source)?;
1331
1332 let mut text_objects_by_capture_ix = Vec::new();
1333 for (ix, name) in query.capture_names().iter().enumerate() {
1334 if let Some(text_object) = TextObject::from_capture_name(name) {
1335 text_objects_by_capture_ix.push((ix as u32, text_object));
1336 }
1337 }
1338
1339 grammar.text_object_config = Some(TextObjectConfig {
1340 query,
1341 text_objects_by_capture_ix,
1342 });
1343 Ok(self)
1344 }
1345
1346 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1347 let grammar = self
1348 .grammar_mut()
1349 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1350 let query = Query::new(&grammar.ts_language, source)?;
1351 let mut item_capture_ix = None;
1352 let mut name_capture_ix = None;
1353 let mut context_capture_ix = None;
1354 let mut collapse_capture_ix = None;
1355 let mut keep_capture_ix = None;
1356 get_capture_indices(
1357 &query,
1358 &mut [
1359 ("item", &mut item_capture_ix),
1360 ("name", &mut name_capture_ix),
1361 ("context", &mut context_capture_ix),
1362 ("keep", &mut keep_capture_ix),
1363 ("collapse", &mut collapse_capture_ix),
1364 ],
1365 );
1366 if let Some(item_capture_ix) = item_capture_ix {
1367 grammar.embedding_config = Some(EmbeddingConfig {
1368 query,
1369 item_capture_ix,
1370 name_capture_ix,
1371 context_capture_ix,
1372 collapse_capture_ix,
1373 keep_capture_ix,
1374 });
1375 }
1376 Ok(self)
1377 }
1378
1379 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1380 let grammar = self
1381 .grammar_mut()
1382 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1383 let query = Query::new(&grammar.ts_language, source)?;
1384 let mut open_capture_ix = None;
1385 let mut close_capture_ix = None;
1386 get_capture_indices(
1387 &query,
1388 &mut [
1389 ("open", &mut open_capture_ix),
1390 ("close", &mut close_capture_ix),
1391 ],
1392 );
1393 let patterns = (0..query.pattern_count())
1394 .map(|ix| {
1395 let mut config = BracketsPatternConfig::default();
1396 for setting in query.property_settings(ix) {
1397 match setting.key.as_ref() {
1398 "newline.only" => config.newline_only = true,
1399 _ => {}
1400 }
1401 }
1402 config
1403 })
1404 .collect();
1405 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1406 grammar.brackets_config = Some(BracketsConfig {
1407 query,
1408 open_capture_ix,
1409 close_capture_ix,
1410 patterns,
1411 });
1412 }
1413 Ok(self)
1414 }
1415
1416 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1417 let grammar = self
1418 .grammar_mut()
1419 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1420 let query = Query::new(&grammar.ts_language, source)?;
1421 let mut indent_capture_ix = None;
1422 let mut start_capture_ix = None;
1423 let mut end_capture_ix = None;
1424 let mut outdent_capture_ix = None;
1425 get_capture_indices(
1426 &query,
1427 &mut [
1428 ("indent", &mut indent_capture_ix),
1429 ("start", &mut start_capture_ix),
1430 ("end", &mut end_capture_ix),
1431 ("outdent", &mut outdent_capture_ix),
1432 ],
1433 );
1434 if let Some(indent_capture_ix) = indent_capture_ix {
1435 grammar.indents_config = Some(IndentConfig {
1436 query,
1437 indent_capture_ix,
1438 start_capture_ix,
1439 end_capture_ix,
1440 outdent_capture_ix,
1441 });
1442 }
1443 Ok(self)
1444 }
1445
1446 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1447 let grammar = self
1448 .grammar_mut()
1449 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1450 let query = Query::new(&grammar.ts_language, source)?;
1451 let mut language_capture_ix = None;
1452 let mut injection_language_capture_ix = None;
1453 let mut content_capture_ix = None;
1454 let mut injection_content_capture_ix = None;
1455 get_capture_indices(
1456 &query,
1457 &mut [
1458 ("language", &mut language_capture_ix),
1459 ("injection.language", &mut injection_language_capture_ix),
1460 ("content", &mut content_capture_ix),
1461 ("injection.content", &mut injection_content_capture_ix),
1462 ],
1463 );
1464 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1465 (None, Some(ix)) => Some(ix),
1466 (Some(_), Some(_)) => {
1467 return Err(anyhow!(
1468 "both language and injection.language captures are present"
1469 ));
1470 }
1471 _ => language_capture_ix,
1472 };
1473 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1474 (None, Some(ix)) => Some(ix),
1475 (Some(_), Some(_)) => {
1476 return Err(anyhow!(
1477 "both content and injection.content captures are present"
1478 ));
1479 }
1480 _ => content_capture_ix,
1481 };
1482 let patterns = (0..query.pattern_count())
1483 .map(|ix| {
1484 let mut config = InjectionPatternConfig::default();
1485 for setting in query.property_settings(ix) {
1486 match setting.key.as_ref() {
1487 "language" | "injection.language" => {
1488 config.language.clone_from(&setting.value);
1489 }
1490 "combined" | "injection.combined" => {
1491 config.combined = true;
1492 }
1493 _ => {}
1494 }
1495 }
1496 config
1497 })
1498 .collect();
1499 if let Some(content_capture_ix) = content_capture_ix {
1500 grammar.injection_config = Some(InjectionConfig {
1501 query,
1502 language_capture_ix,
1503 content_capture_ix,
1504 patterns,
1505 });
1506 }
1507 Ok(self)
1508 }
1509
1510 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1511 let query = {
1512 let grammar = self
1513 .grammar
1514 .as_ref()
1515 .ok_or_else(|| anyhow!("no grammar for language"))?;
1516 Query::new(&grammar.ts_language, source)?
1517 };
1518
1519 let mut override_configs_by_id = HashMap::default();
1520 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1521 let mut range_is_inclusive = false;
1522 if name.starts_with('_') {
1523 continue;
1524 }
1525 if let Some(prefix) = name.strip_suffix(".inclusive") {
1526 name = prefix;
1527 range_is_inclusive = true;
1528 }
1529
1530 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1531 for server_name in &value.opt_into_language_servers {
1532 if !self
1533 .config
1534 .scope_opt_in_language_servers
1535 .contains(server_name)
1536 {
1537 util::debug_panic!(
1538 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1539 );
1540 }
1541 }
1542
1543 override_configs_by_id.insert(
1544 ix as u32,
1545 OverrideEntry {
1546 name: name.to_string(),
1547 range_is_inclusive,
1548 value,
1549 },
1550 );
1551 }
1552
1553 let referenced_override_names = self.config.overrides.keys().chain(
1554 self.config
1555 .brackets
1556 .disabled_scopes_by_bracket_ix
1557 .iter()
1558 .flatten(),
1559 );
1560
1561 for referenced_name in referenced_override_names {
1562 if !override_configs_by_id
1563 .values()
1564 .any(|entry| entry.name == *referenced_name)
1565 {
1566 Err(anyhow!(
1567 "language {:?} has overrides in config not in query: {referenced_name:?}",
1568 self.config.name
1569 ))?;
1570 }
1571 }
1572
1573 for entry in override_configs_by_id.values_mut() {
1574 entry.value.disabled_bracket_ixs = self
1575 .config
1576 .brackets
1577 .disabled_scopes_by_bracket_ix
1578 .iter()
1579 .enumerate()
1580 .filter_map(|(ix, disabled_scope_names)| {
1581 if disabled_scope_names.contains(&entry.name) {
1582 Some(ix as u16)
1583 } else {
1584 None
1585 }
1586 })
1587 .collect();
1588 }
1589
1590 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1591
1592 let grammar = self
1593 .grammar_mut()
1594 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1595 grammar.override_config = Some(OverrideConfig {
1596 query,
1597 values: override_configs_by_id,
1598 });
1599 Ok(self)
1600 }
1601
1602 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1603 let grammar = self
1604 .grammar_mut()
1605 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1606
1607 let query = Query::new(&grammar.ts_language, source)?;
1608 let mut redaction_capture_ix = None;
1609 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1610
1611 if let Some(redaction_capture_ix) = redaction_capture_ix {
1612 grammar.redactions_config = Some(RedactionConfig {
1613 query,
1614 redaction_capture_ix,
1615 });
1616 }
1617
1618 Ok(self)
1619 }
1620
1621 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1622 Arc::get_mut(self.grammar.as_mut()?)
1623 }
1624
1625 pub fn name(&self) -> LanguageName {
1626 self.config.name.clone()
1627 }
1628
1629 pub fn code_fence_block_name(&self) -> Arc<str> {
1630 self.config
1631 .code_fence_block_name
1632 .clone()
1633 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1634 }
1635
1636 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1637 self.context_provider.clone()
1638 }
1639
1640 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1641 self.toolchain.clone()
1642 }
1643
1644 pub fn highlight_text<'a>(
1645 self: &'a Arc<Self>,
1646 text: &'a Rope,
1647 range: Range<usize>,
1648 ) -> Vec<(Range<usize>, HighlightId)> {
1649 let mut result = Vec::new();
1650 if let Some(grammar) = &self.grammar {
1651 let tree = grammar.parse_text(text, None);
1652 let captures =
1653 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1654 grammar.highlights_query.as_ref()
1655 });
1656 let highlight_maps = vec![grammar.highlight_map()];
1657 let mut offset = 0;
1658 for chunk in
1659 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1660 {
1661 let end_offset = offset + chunk.text.len();
1662 if let Some(highlight_id) = chunk.syntax_highlight_id {
1663 if !highlight_id.is_default() {
1664 result.push((offset..end_offset, highlight_id));
1665 }
1666 }
1667 offset = end_offset;
1668 }
1669 }
1670 result
1671 }
1672
1673 pub fn path_suffixes(&self) -> &[String] {
1674 &self.config.matcher.path_suffixes
1675 }
1676
1677 pub fn should_autoclose_before(&self, c: char) -> bool {
1678 c.is_whitespace() || self.config.autoclose_before.contains(c)
1679 }
1680
1681 pub fn set_theme(&self, theme: &SyntaxTheme) {
1682 if let Some(grammar) = self.grammar.as_ref() {
1683 if let Some(highlights_query) = &grammar.highlights_query {
1684 *grammar.highlight_map.lock() =
1685 HighlightMap::new(highlights_query.capture_names(), theme);
1686 }
1687 }
1688 }
1689
1690 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1691 self.grammar.as_ref()
1692 }
1693
1694 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1695 LanguageScope {
1696 language: self.clone(),
1697 override_id: None,
1698 }
1699 }
1700
1701 pub fn lsp_id(&self) -> String {
1702 self.config.name.lsp_id()
1703 }
1704
1705 pub fn prettier_parser_name(&self) -> Option<&str> {
1706 self.config.prettier_parser_name.as_deref()
1707 }
1708
1709 pub fn config(&self) -> &LanguageConfig {
1710 &self.config
1711 }
1712}
1713
1714impl LanguageScope {
1715 pub fn path_suffixes(&self) -> &[String] {
1716 &self.language.path_suffixes()
1717 }
1718
1719 pub fn language_name(&self) -> LanguageName {
1720 self.language.config.name.clone()
1721 }
1722
1723 pub fn collapsed_placeholder(&self) -> &str {
1724 self.language.config.collapsed_placeholder.as_ref()
1725 }
1726
1727 /// Returns line prefix that is inserted in e.g. line continuations or
1728 /// in `toggle comments` action.
1729 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1730 Override::as_option(
1731 self.config_override().map(|o| &o.line_comments),
1732 Some(&self.language.config.line_comments),
1733 )
1734 .map_or([].as_slice(), |e| e.as_slice())
1735 }
1736
1737 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1738 Override::as_option(
1739 self.config_override().map(|o| &o.block_comment),
1740 self.language.config.block_comment.as_ref(),
1741 )
1742 .map(|e| (&e.0, &e.1))
1743 }
1744
1745 /// Returns a list of language-specific word characters.
1746 ///
1747 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1748 /// the purpose of actions like 'move to next word end` or whole-word search.
1749 /// It additionally accounts for language's additional word characters.
1750 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1751 Override::as_option(
1752 self.config_override().map(|o| &o.word_characters),
1753 Some(&self.language.config.word_characters),
1754 )
1755 }
1756
1757 /// Returns a list of language-specific characters that are considered part of
1758 /// a completion query.
1759 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1760 Override::as_option(
1761 self.config_override()
1762 .map(|o| &o.completion_query_characters),
1763 Some(&self.language.config.completion_query_characters),
1764 )
1765 }
1766
1767 /// Returns a list of bracket pairs for a given language with an additional
1768 /// piece of information about whether the particular bracket pair is currently active for a given language.
1769 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1770 let mut disabled_ids = self
1771 .config_override()
1772 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1773 self.language
1774 .config
1775 .brackets
1776 .pairs
1777 .iter()
1778 .enumerate()
1779 .map(move |(ix, bracket)| {
1780 let mut is_enabled = true;
1781 if let Some(next_disabled_ix) = disabled_ids.first() {
1782 if ix == *next_disabled_ix as usize {
1783 disabled_ids = &disabled_ids[1..];
1784 is_enabled = false;
1785 }
1786 }
1787 (bracket, is_enabled)
1788 })
1789 }
1790
1791 pub fn should_autoclose_before(&self, c: char) -> bool {
1792 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1793 }
1794
1795 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1796 let config = &self.language.config;
1797 let opt_in_servers = &config.scope_opt_in_language_servers;
1798 if opt_in_servers.iter().any(|o| *o == *name) {
1799 if let Some(over) = self.config_override() {
1800 over.opt_into_language_servers.iter().any(|o| *o == *name)
1801 } else {
1802 false
1803 }
1804 } else {
1805 true
1806 }
1807 }
1808
1809 pub fn override_name(&self) -> Option<&str> {
1810 let id = self.override_id?;
1811 let grammar = self.language.grammar.as_ref()?;
1812 let override_config = grammar.override_config.as_ref()?;
1813 override_config.values.get(&id).map(|e| e.name.as_str())
1814 }
1815
1816 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1817 let id = self.override_id?;
1818 let grammar = self.language.grammar.as_ref()?;
1819 let override_config = grammar.override_config.as_ref()?;
1820 override_config.values.get(&id).map(|e| &e.value)
1821 }
1822}
1823
1824impl Hash for Language {
1825 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1826 self.id.hash(state)
1827 }
1828}
1829
1830impl PartialEq for Language {
1831 fn eq(&self, other: &Self) -> bool {
1832 self.id.eq(&other.id)
1833 }
1834}
1835
1836impl Eq for Language {}
1837
1838impl Debug for Language {
1839 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1840 f.debug_struct("Language")
1841 .field("name", &self.config.name)
1842 .finish()
1843 }
1844}
1845
1846impl Grammar {
1847 pub fn id(&self) -> GrammarId {
1848 self.id
1849 }
1850
1851 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1852 with_parser(|parser| {
1853 parser
1854 .set_language(&self.ts_language)
1855 .expect("incompatible grammar");
1856 let mut chunks = text.chunks_in_range(0..text.len());
1857 parser
1858 .parse_with_options(
1859 &mut move |offset, _| {
1860 chunks.seek(offset);
1861 chunks.next().unwrap_or("").as_bytes()
1862 },
1863 old_tree.as_ref(),
1864 None,
1865 )
1866 .unwrap()
1867 })
1868 }
1869
1870 pub fn highlight_map(&self) -> HighlightMap {
1871 self.highlight_map.lock().clone()
1872 }
1873
1874 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1875 let capture_id = self
1876 .highlights_query
1877 .as_ref()?
1878 .capture_index_for_name(name)?;
1879 Some(self.highlight_map.lock().get(capture_id))
1880 }
1881}
1882
1883impl CodeLabel {
1884 pub fn fallback_for_completion(
1885 item: &lsp::CompletionItem,
1886 language: Option<&Language>,
1887 ) -> Self {
1888 let highlight_id = item.kind.and_then(|kind| {
1889 let grammar = language?.grammar()?;
1890 use lsp::CompletionItemKind as Kind;
1891 match kind {
1892 Kind::CLASS => grammar.highlight_id_for_name("type"),
1893 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
1894 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
1895 Kind::ENUM => grammar
1896 .highlight_id_for_name("enum")
1897 .or_else(|| grammar.highlight_id_for_name("type")),
1898 Kind::FIELD => grammar.highlight_id_for_name("property"),
1899 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
1900 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
1901 Kind::METHOD => grammar
1902 .highlight_id_for_name("function.method")
1903 .or_else(|| grammar.highlight_id_for_name("function")),
1904 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
1905 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
1906 Kind::STRUCT => grammar.highlight_id_for_name("type"),
1907 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
1908 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
1909 _ => None,
1910 }
1911 });
1912
1913 let label = &item.label;
1914 let label_length = label.len();
1915 let runs = highlight_id
1916 .map(|highlight_id| vec![(0..label_length, highlight_id)])
1917 .unwrap_or_default();
1918 let text = if let Some(detail) = &item.detail {
1919 format!("{label} {detail}")
1920 } else if let Some(description) = item
1921 .label_details
1922 .as_ref()
1923 .and_then(|label_details| label_details.description.as_ref())
1924 {
1925 format!("{label} {description}")
1926 } else {
1927 label.clone()
1928 };
1929 Self {
1930 text,
1931 runs,
1932 filter_range: 0..label_length,
1933 }
1934 }
1935
1936 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1937 let mut result = Self {
1938 runs: Vec::new(),
1939 filter_range: 0..text.len(),
1940 text,
1941 };
1942 if let Some(filter_text) = filter_text {
1943 if let Some(ix) = result.text.find(filter_text) {
1944 result.filter_range = ix..ix + filter_text.len();
1945 }
1946 }
1947 result
1948 }
1949
1950 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1951 let start_ix = self.text.len();
1952 self.text.push_str(text);
1953 let end_ix = self.text.len();
1954 if let Some(highlight) = highlight {
1955 self.runs.push((start_ix..end_ix, highlight));
1956 }
1957 }
1958
1959 pub fn text(&self) -> &str {
1960 self.text.as_str()
1961 }
1962
1963 pub fn filter_text(&self) -> &str {
1964 &self.text[self.filter_range.clone()]
1965 }
1966}
1967
1968impl From<String> for CodeLabel {
1969 fn from(value: String) -> Self {
1970 Self::plain(value, None)
1971 }
1972}
1973
1974impl From<&str> for CodeLabel {
1975 fn from(value: &str) -> Self {
1976 Self::plain(value.to_string(), None)
1977 }
1978}
1979
1980impl Ord for LanguageMatcher {
1981 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1982 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1983 self.first_line_pattern
1984 .as_ref()
1985 .map(Regex::as_str)
1986 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1987 })
1988 }
1989}
1990
1991impl PartialOrd for LanguageMatcher {
1992 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1993 Some(self.cmp(other))
1994 }
1995}
1996
1997impl Eq for LanguageMatcher {}
1998
1999impl PartialEq for LanguageMatcher {
2000 fn eq(&self, other: &Self) -> bool {
2001 self.path_suffixes == other.path_suffixes
2002 && self.first_line_pattern.as_ref().map(Regex::as_str)
2003 == other.first_line_pattern.as_ref().map(Regex::as_str)
2004 }
2005}
2006
2007#[cfg(any(test, feature = "test-support"))]
2008impl Default for FakeLspAdapter {
2009 fn default() -> Self {
2010 Self {
2011 name: "the-fake-language-server",
2012 capabilities: lsp::LanguageServer::full_capabilities(),
2013 initializer: None,
2014 disk_based_diagnostics_progress_token: None,
2015 initialization_options: None,
2016 disk_based_diagnostics_sources: Vec::new(),
2017 prettier_plugins: Vec::new(),
2018 language_server_binary: LanguageServerBinary {
2019 path: "/the/fake/lsp/path".into(),
2020 arguments: vec![],
2021 env: Default::default(),
2022 },
2023 label_for_completion: None,
2024 }
2025 }
2026}
2027
2028#[cfg(any(test, feature = "test-support"))]
2029#[async_trait(?Send)]
2030impl LspAdapter for FakeLspAdapter {
2031 fn name(&self) -> LanguageServerName {
2032 LanguageServerName(self.name.into())
2033 }
2034
2035 async fn check_if_user_installed(
2036 &self,
2037 _: &dyn LspAdapterDelegate,
2038 _: Arc<dyn LanguageToolchainStore>,
2039 _: &AsyncApp,
2040 ) -> Option<LanguageServerBinary> {
2041 Some(self.language_server_binary.clone())
2042 }
2043
2044 fn get_language_server_command<'a>(
2045 self: Arc<Self>,
2046 _: Arc<dyn LspAdapterDelegate>,
2047 _: Arc<dyn LanguageToolchainStore>,
2048 _: LanguageServerBinaryOptions,
2049 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2050 _: &'a mut AsyncApp,
2051 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2052 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2053 }
2054
2055 async fn fetch_latest_server_version(
2056 &self,
2057 _: &dyn LspAdapterDelegate,
2058 ) -> Result<Box<dyn 'static + Send + Any>> {
2059 unreachable!();
2060 }
2061
2062 async fn fetch_server_binary(
2063 &self,
2064 _: Box<dyn 'static + Send + Any>,
2065 _: PathBuf,
2066 _: &dyn LspAdapterDelegate,
2067 ) -> Result<LanguageServerBinary> {
2068 unreachable!();
2069 }
2070
2071 async fn cached_server_binary(
2072 &self,
2073 _: PathBuf,
2074 _: &dyn LspAdapterDelegate,
2075 ) -> Option<LanguageServerBinary> {
2076 unreachable!();
2077 }
2078
2079 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2080 self.disk_based_diagnostics_sources.clone()
2081 }
2082
2083 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2084 self.disk_based_diagnostics_progress_token.clone()
2085 }
2086
2087 async fn initialization_options(
2088 self: Arc<Self>,
2089 _: &dyn Fs,
2090 _: &Arc<dyn LspAdapterDelegate>,
2091 ) -> Result<Option<Value>> {
2092 Ok(self.initialization_options.clone())
2093 }
2094
2095 async fn label_for_completion(
2096 &self,
2097 item: &lsp::CompletionItem,
2098 language: &Arc<Language>,
2099 ) -> Option<CodeLabel> {
2100 let label_for_completion = self.label_for_completion.as_ref()?;
2101 label_for_completion(item, language)
2102 }
2103}
2104
2105fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2106 for (ix, name) in query.capture_names().iter().enumerate() {
2107 for (capture_name, index) in captures.iter_mut() {
2108 if capture_name == name {
2109 **index = Some(ix as u32);
2110 break;
2111 }
2112 }
2113 }
2114}
2115
2116pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2117 lsp::Position::new(point.row, point.column)
2118}
2119
2120pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2121 Unclipped(PointUtf16::new(point.line, point.character))
2122}
2123
2124pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2125 if range.start > range.end {
2126 Err(anyhow!(
2127 "Inverted range provided to an LSP request: {:?}-{:?}",
2128 range.start,
2129 range.end
2130 ))
2131 } else {
2132 Ok(lsp::Range {
2133 start: point_to_lsp(range.start),
2134 end: point_to_lsp(range.end),
2135 })
2136 }
2137}
2138
2139pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2140 let mut start = point_from_lsp(range.start);
2141 let mut end = point_from_lsp(range.end);
2142 if start > end {
2143 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2144 mem::swap(&mut start, &mut end);
2145 }
2146 start..end
2147}
2148
2149#[cfg(test)]
2150mod tests {
2151 use super::*;
2152 use gpui::TestAppContext;
2153
2154 #[gpui::test(iterations = 10)]
2155 async fn test_language_loading(cx: &mut TestAppContext) {
2156 let languages = LanguageRegistry::test(cx.executor());
2157 let languages = Arc::new(languages);
2158 languages.register_native_grammars([
2159 ("json", tree_sitter_json::LANGUAGE),
2160 ("rust", tree_sitter_rust::LANGUAGE),
2161 ]);
2162 languages.register_test_language(LanguageConfig {
2163 name: "JSON".into(),
2164 grammar: Some("json".into()),
2165 matcher: LanguageMatcher {
2166 path_suffixes: vec!["json".into()],
2167 ..Default::default()
2168 },
2169 ..Default::default()
2170 });
2171 languages.register_test_language(LanguageConfig {
2172 name: "Rust".into(),
2173 grammar: Some("rust".into()),
2174 matcher: LanguageMatcher {
2175 path_suffixes: vec!["rs".into()],
2176 ..Default::default()
2177 },
2178 ..Default::default()
2179 });
2180 assert_eq!(
2181 languages.language_names(),
2182 &[
2183 "JSON".to_string(),
2184 "Plain Text".to_string(),
2185 "Rust".to_string(),
2186 ]
2187 );
2188
2189 let rust1 = languages.language_for_name("Rust");
2190 let rust2 = languages.language_for_name("Rust");
2191
2192 // Ensure language is still listed even if it's being loaded.
2193 assert_eq!(
2194 languages.language_names(),
2195 &[
2196 "JSON".to_string(),
2197 "Plain Text".to_string(),
2198 "Rust".to_string(),
2199 ]
2200 );
2201
2202 let (rust1, rust2) = futures::join!(rust1, rust2);
2203 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2204
2205 // Ensure language is still listed even after loading it.
2206 assert_eq!(
2207 languages.language_names(),
2208 &[
2209 "JSON".to_string(),
2210 "Plain Text".to_string(),
2211 "Rust".to_string(),
2212 ]
2213 );
2214
2215 // Loading an unknown language returns an error.
2216 assert!(languages.language_for_name("Unknown").await.is_err());
2217 }
2218}