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 None
554 }
555
556 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
557 Default::default()
558 }
559
560 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
561 None
562 }
563
564 fn language_ids(&self) -> HashMap<String, String> {
565 Default::default()
566 }
567
568 /// Support custom initialize params.
569 fn prepare_initialize_params(
570 &self,
571 original: InitializeParams,
572 _: &App,
573 ) -> Result<InitializeParams> {
574 Ok(original)
575 }
576
577 fn attach_kind(&self) -> Attach {
578 Attach::Shared
579 }
580
581 fn manifest_name(&self) -> Option<ManifestName> {
582 None
583 }
584
585 /// Method only implemented by the default JSON language server adapter.
586 /// Used to provide dynamic reloading of the JSON schemas used to
587 /// provide autocompletion and diagnostics in Zed setting and keybind
588 /// files
589 fn is_primary_zed_json_schema_adapter(&self) -> bool {
590 false
591 }
592
593 /// Method only implemented by the default JSON language server adapter.
594 /// Used to clear the cache of JSON schemas that are used to provide
595 /// autocompletion and diagnostics in Zed settings and keybinds files.
596 /// Should not be called unless the callee is sure that
597 /// `Self::is_primary_zed_json_schema_adapter` returns `true`
598 async fn clear_zed_json_schema_cache(&self) {
599 unreachable!(
600 "Not implemented for this adapter. This method should only be called on the default JSON language server adapter"
601 );
602 }
603}
604
605async fn try_fetch_server_binary<L: LspAdapter + 'static + Send + Sync + ?Sized>(
606 adapter: &L,
607 delegate: &Arc<dyn LspAdapterDelegate>,
608 container_dir: PathBuf,
609 cx: &mut AsyncApp,
610) -> Result<LanguageServerBinary> {
611 if let Some(task) = adapter.will_fetch_server(delegate, cx) {
612 task.await?;
613 }
614
615 let name = adapter.name();
616 log::info!("fetching latest version of language server {:?}", name.0);
617 delegate.update_status(name.clone(), BinaryStatus::CheckingForUpdate);
618
619 let latest_version = adapter
620 .fetch_latest_server_version(delegate.as_ref())
621 .await?;
622
623 if let Some(binary) = adapter
624 .check_if_version_installed(latest_version.as_ref(), &container_dir, delegate.as_ref())
625 .await
626 {
627 log::info!("language server {:?} is already installed", name.0);
628 delegate.update_status(name.clone(), BinaryStatus::None);
629 Ok(binary)
630 } else {
631 log::info!("downloading language server {:?}", name.0);
632 delegate.update_status(adapter.name(), BinaryStatus::Downloading);
633 let binary = adapter
634 .fetch_server_binary(latest_version, container_dir, delegate.as_ref())
635 .await;
636
637 delegate.update_status(name.clone(), BinaryStatus::None);
638 binary
639 }
640}
641
642#[derive(Clone, Debug, Default, PartialEq, Eq)]
643pub struct CodeLabel {
644 /// The text to display.
645 pub text: String,
646 /// Syntax highlighting runs.
647 pub runs: Vec<(Range<usize>, HighlightId)>,
648 /// The portion of the text that should be used in fuzzy filtering.
649 pub filter_range: Range<usize>,
650}
651
652#[derive(Clone, Deserialize, JsonSchema)]
653pub struct LanguageConfig {
654 /// Human-readable name of the language.
655 pub name: LanguageName,
656 /// The name of this language for a Markdown code fence block
657 pub code_fence_block_name: Option<Arc<str>>,
658 // The name of the grammar in a WASM bundle (experimental).
659 pub grammar: Option<Arc<str>>,
660 /// The criteria for matching this language to a given file.
661 #[serde(flatten)]
662 pub matcher: LanguageMatcher,
663 /// List of bracket types in a language.
664 #[serde(default)]
665 #[schemars(schema_with = "bracket_pair_config_json_schema")]
666 pub brackets: BracketPairConfig,
667 /// If set to true, auto indentation uses last non empty line to determine
668 /// the indentation level for a new line.
669 #[serde(default = "auto_indent_using_last_non_empty_line_default")]
670 pub auto_indent_using_last_non_empty_line: bool,
671 // Whether indentation of pasted content should be adjusted based on the context.
672 #[serde(default)]
673 pub auto_indent_on_paste: Option<bool>,
674 /// A regex that is used to determine whether the indentation level should be
675 /// increased in the following line.
676 #[serde(default, deserialize_with = "deserialize_regex")]
677 #[schemars(schema_with = "regex_json_schema")]
678 pub increase_indent_pattern: Option<Regex>,
679 /// A regex that is used to determine whether the indentation level should be
680 /// decreased in the following line.
681 #[serde(default, deserialize_with = "deserialize_regex")]
682 #[schemars(schema_with = "regex_json_schema")]
683 pub decrease_indent_pattern: Option<Regex>,
684 /// A list of characters that trigger the automatic insertion of a closing
685 /// bracket when they immediately precede the point where an opening
686 /// bracket is inserted.
687 #[serde(default)]
688 pub autoclose_before: String,
689 /// A placeholder used internally by Semantic Index.
690 #[serde(default)]
691 pub collapsed_placeholder: String,
692 /// A line comment string that is inserted in e.g. `toggle comments` action.
693 /// A language can have multiple flavours of line comments. All of the provided line comments are
694 /// used for comment continuations on the next line, but only the first one is used for Editor::ToggleComments.
695 #[serde(default)]
696 pub line_comments: Vec<Arc<str>>,
697 /// Starting and closing characters of a block comment.
698 #[serde(default)]
699 pub block_comment: Option<(Arc<str>, Arc<str>)>,
700 /// A list of language servers that are allowed to run on subranges of a given language.
701 #[serde(default)]
702 pub scope_opt_in_language_servers: Vec<LanguageServerName>,
703 #[serde(default)]
704 pub overrides: HashMap<String, LanguageConfigOverride>,
705 /// A list of characters that Zed should treat as word characters for the
706 /// purpose of features that operate on word boundaries, like 'move to next word end'
707 /// or a whole-word search in buffer search.
708 #[serde(default)]
709 pub word_characters: HashSet<char>,
710 /// Whether to indent lines using tab characters, as opposed to multiple
711 /// spaces.
712 #[serde(default)]
713 pub hard_tabs: Option<bool>,
714 /// How many columns a tab should occupy.
715 #[serde(default)]
716 pub tab_size: Option<NonZeroU32>,
717 /// How to soft-wrap long lines of text.
718 #[serde(default)]
719 pub soft_wrap: Option<SoftWrap>,
720 /// The name of a Prettier parser that will be used for this language when no file path is available.
721 /// If there's a parser name in the language settings, that will be used instead.
722 #[serde(default)]
723 pub prettier_parser_name: Option<String>,
724 /// If true, this language is only for syntax highlighting via an injection into other
725 /// languages, but should not appear to the user as a distinct language.
726 #[serde(default)]
727 pub hidden: bool,
728 /// If configured, this language contains JSX style tags, and should support auto-closing of those tags.
729 #[serde(default)]
730 pub jsx_tag_auto_close: Option<JsxTagAutoCloseConfig>,
731 /// A list of characters that Zed should treat as word characters for completion queries.
732 #[serde(default)]
733 pub completion_query_characters: HashSet<char>,
734}
735
736#[derive(Clone, Debug, Serialize, Deserialize, Default, JsonSchema)]
737pub struct LanguageMatcher {
738 /// 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`.
739 #[serde(default)]
740 pub path_suffixes: Vec<String>,
741 /// A regex pattern that determines whether the language should be assigned to a file or not.
742 #[serde(
743 default,
744 serialize_with = "serialize_regex",
745 deserialize_with = "deserialize_regex"
746 )]
747 #[schemars(schema_with = "regex_json_schema")]
748 pub first_line_pattern: Option<Regex>,
749}
750
751/// The configuration for JSX tag auto-closing.
752#[derive(Clone, Deserialize, JsonSchema)]
753pub struct JsxTagAutoCloseConfig {
754 /// The name of the node for a opening tag
755 pub open_tag_node_name: String,
756 /// The name of the node for an closing tag
757 pub close_tag_node_name: String,
758 /// The name of the node for a complete element with children for open and close tags
759 pub jsx_element_node_name: String,
760 /// The name of the node found within both opening and closing
761 /// tags that describes the tag name
762 pub tag_name_node_name: String,
763 /// Alternate Node names for tag names.
764 /// Specifically needed as TSX represents the name in `<Foo.Bar>`
765 /// as `member_expression` rather than `identifier` as usual
766 #[serde(default)]
767 pub tag_name_node_name_alternates: Vec<String>,
768 /// Some grammars are smart enough to detect a closing tag
769 /// that is not valid i.e. doesn't match it's corresponding
770 /// opening tag or does not have a corresponding opening tag
771 /// This should be set to the name of the node for invalid
772 /// closing tags if the grammar contains such a node, otherwise
773 /// detecting already closed tags will not work properly
774 #[serde(default)]
775 pub erroneous_close_tag_node_name: Option<String>,
776 /// See above for erroneous_close_tag_node_name for details
777 /// This should be set if the node used for the tag name
778 /// within erroneous closing tags is different from the
779 /// normal tag name node name
780 #[serde(default)]
781 pub erroneous_close_tag_name_node_name: Option<String>,
782}
783
784/// Represents a language for the given range. Some languages (e.g. HTML)
785/// interleave several languages together, thus a single buffer might actually contain
786/// several nested scopes.
787#[derive(Clone, Debug)]
788pub struct LanguageScope {
789 language: Arc<Language>,
790 override_id: Option<u32>,
791}
792
793#[derive(Clone, Deserialize, Default, Debug, JsonSchema)]
794pub struct LanguageConfigOverride {
795 #[serde(default)]
796 pub line_comments: Override<Vec<Arc<str>>>,
797 #[serde(default)]
798 pub block_comment: Override<(Arc<str>, Arc<str>)>,
799 #[serde(skip)]
800 pub disabled_bracket_ixs: Vec<u16>,
801 #[serde(default)]
802 pub word_characters: Override<HashSet<char>>,
803 #[serde(default)]
804 pub completion_query_characters: Override<HashSet<char>>,
805 #[serde(default)]
806 pub opt_into_language_servers: Vec<LanguageServerName>,
807}
808
809#[derive(Clone, Deserialize, Debug, Serialize, JsonSchema)]
810#[serde(untagged)]
811pub enum Override<T> {
812 Remove { remove: bool },
813 Set(T),
814}
815
816impl<T> Default for Override<T> {
817 fn default() -> Self {
818 Override::Remove { remove: false }
819 }
820}
821
822impl<T> Override<T> {
823 fn as_option<'a>(this: Option<&'a Self>, original: Option<&'a T>) -> Option<&'a T> {
824 match this {
825 Some(Self::Set(value)) => Some(value),
826 Some(Self::Remove { remove: true }) => None,
827 Some(Self::Remove { remove: false }) | None => original,
828 }
829 }
830}
831
832impl Default for LanguageConfig {
833 fn default() -> Self {
834 Self {
835 name: LanguageName::new(""),
836 code_fence_block_name: None,
837 grammar: None,
838 matcher: LanguageMatcher::default(),
839 brackets: Default::default(),
840 auto_indent_using_last_non_empty_line: auto_indent_using_last_non_empty_line_default(),
841 auto_indent_on_paste: None,
842 increase_indent_pattern: Default::default(),
843 decrease_indent_pattern: Default::default(),
844 autoclose_before: Default::default(),
845 line_comments: Default::default(),
846 block_comment: Default::default(),
847 scope_opt_in_language_servers: Default::default(),
848 overrides: Default::default(),
849 word_characters: Default::default(),
850 collapsed_placeholder: Default::default(),
851 hard_tabs: None,
852 tab_size: None,
853 soft_wrap: None,
854 prettier_parser_name: None,
855 hidden: false,
856 jsx_tag_auto_close: None,
857 completion_query_characters: Default::default(),
858 }
859 }
860}
861
862fn auto_indent_using_last_non_empty_line_default() -> bool {
863 true
864}
865
866fn deserialize_regex<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Regex>, D::Error> {
867 let source = Option::<String>::deserialize(d)?;
868 if let Some(source) = source {
869 Ok(Some(regex::Regex::new(&source).map_err(de::Error::custom)?))
870 } else {
871 Ok(None)
872 }
873}
874
875fn regex_json_schema(_: &mut SchemaGenerator) -> Schema {
876 Schema::Object(SchemaObject {
877 instance_type: Some(InstanceType::String.into()),
878 ..Default::default()
879 })
880}
881
882fn serialize_regex<S>(regex: &Option<Regex>, serializer: S) -> Result<S::Ok, S::Error>
883where
884 S: Serializer,
885{
886 match regex {
887 Some(regex) => serializer.serialize_str(regex.as_str()),
888 None => serializer.serialize_none(),
889 }
890}
891
892#[doc(hidden)]
893#[cfg(any(test, feature = "test-support"))]
894pub struct FakeLspAdapter {
895 pub name: &'static str,
896 pub initialization_options: Option<Value>,
897 pub prettier_plugins: Vec<&'static str>,
898 pub disk_based_diagnostics_progress_token: Option<String>,
899 pub disk_based_diagnostics_sources: Vec<String>,
900 pub language_server_binary: LanguageServerBinary,
901
902 pub capabilities: lsp::ServerCapabilities,
903 pub initializer: Option<Box<dyn 'static + Send + Sync + Fn(&mut lsp::FakeLanguageServer)>>,
904 pub label_for_completion: Option<
905 Box<
906 dyn 'static
907 + Send
908 + Sync
909 + Fn(&lsp::CompletionItem, &Arc<Language>) -> Option<CodeLabel>,
910 >,
911 >,
912}
913
914/// Configuration of handling bracket pairs for a given language.
915///
916/// This struct includes settings for defining which pairs of characters are considered brackets and
917/// also specifies any language-specific scopes where these pairs should be ignored for bracket matching purposes.
918#[derive(Clone, Debug, Default, JsonSchema)]
919pub struct BracketPairConfig {
920 /// A list of character pairs that should be treated as brackets in the context of a given language.
921 pub pairs: Vec<BracketPair>,
922 /// A list of tree-sitter scopes for which a given bracket should not be active.
923 /// N-th entry in `[Self::disabled_scopes_by_bracket_ix]` contains a list of disabled scopes for an n-th entry in `[Self::pairs]`
924 #[serde(skip)]
925 pub disabled_scopes_by_bracket_ix: Vec<Vec<String>>,
926}
927
928impl BracketPairConfig {
929 pub fn is_closing_brace(&self, c: char) -> bool {
930 self.pairs.iter().any(|pair| pair.end.starts_with(c))
931 }
932}
933
934fn bracket_pair_config_json_schema(r#gen: &mut SchemaGenerator) -> Schema {
935 Option::<Vec<BracketPairContent>>::json_schema(r#gen)
936}
937
938#[derive(Deserialize, JsonSchema)]
939pub struct BracketPairContent {
940 #[serde(flatten)]
941 pub bracket_pair: BracketPair,
942 #[serde(default)]
943 pub not_in: Vec<String>,
944}
945
946impl<'de> Deserialize<'de> for BracketPairConfig {
947 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
948 where
949 D: Deserializer<'de>,
950 {
951 let result = Vec::<BracketPairContent>::deserialize(deserializer)?;
952 let mut brackets = Vec::with_capacity(result.len());
953 let mut disabled_scopes_by_bracket_ix = Vec::with_capacity(result.len());
954 for entry in result {
955 brackets.push(entry.bracket_pair);
956 disabled_scopes_by_bracket_ix.push(entry.not_in);
957 }
958
959 Ok(BracketPairConfig {
960 pairs: brackets,
961 disabled_scopes_by_bracket_ix,
962 })
963 }
964}
965
966/// Describes a single bracket pair and how an editor should react to e.g. inserting
967/// an opening bracket or to a newline character insertion in between `start` and `end` characters.
968#[derive(Clone, Debug, Default, Deserialize, PartialEq, JsonSchema)]
969pub struct BracketPair {
970 /// Starting substring for a bracket.
971 pub start: String,
972 /// Ending substring for a bracket.
973 pub end: String,
974 /// True if `end` should be automatically inserted right after `start` characters.
975 pub close: bool,
976 /// True if selected text should be surrounded by `start` and `end` characters.
977 #[serde(default = "default_true")]
978 pub surround: bool,
979 /// True if an extra newline should be inserted while the cursor is in the middle
980 /// of that bracket pair.
981 pub newline: bool,
982}
983
984#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
985pub struct LanguageId(usize);
986
987impl LanguageId {
988 pub(crate) fn new() -> Self {
989 Self(NEXT_LANGUAGE_ID.fetch_add(1, SeqCst))
990 }
991}
992
993pub struct Language {
994 pub(crate) id: LanguageId,
995 pub(crate) config: LanguageConfig,
996 pub(crate) grammar: Option<Arc<Grammar>>,
997 pub(crate) context_provider: Option<Arc<dyn ContextProvider>>,
998 pub(crate) toolchain: Option<Arc<dyn ToolchainLister>>,
999}
1000
1001#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
1002pub struct GrammarId(pub usize);
1003
1004impl GrammarId {
1005 pub(crate) fn new() -> Self {
1006 Self(NEXT_GRAMMAR_ID.fetch_add(1, SeqCst))
1007 }
1008}
1009
1010pub struct Grammar {
1011 id: GrammarId,
1012 pub ts_language: tree_sitter::Language,
1013 pub(crate) error_query: Option<Query>,
1014 pub(crate) highlights_query: Option<Query>,
1015 pub(crate) brackets_config: Option<BracketsConfig>,
1016 pub(crate) redactions_config: Option<RedactionConfig>,
1017 pub(crate) runnable_config: Option<RunnableConfig>,
1018 pub(crate) indents_config: Option<IndentConfig>,
1019 pub outline_config: Option<OutlineConfig>,
1020 pub text_object_config: Option<TextObjectConfig>,
1021 pub embedding_config: Option<EmbeddingConfig>,
1022 pub(crate) injection_config: Option<InjectionConfig>,
1023 pub(crate) override_config: Option<OverrideConfig>,
1024 pub(crate) highlight_map: Mutex<HighlightMap>,
1025}
1026
1027struct IndentConfig {
1028 query: Query,
1029 indent_capture_ix: u32,
1030 start_capture_ix: Option<u32>,
1031 end_capture_ix: Option<u32>,
1032 outdent_capture_ix: Option<u32>,
1033}
1034
1035pub struct OutlineConfig {
1036 pub query: Query,
1037 pub item_capture_ix: u32,
1038 pub name_capture_ix: u32,
1039 pub context_capture_ix: Option<u32>,
1040 pub extra_context_capture_ix: Option<u32>,
1041 pub open_capture_ix: Option<u32>,
1042 pub close_capture_ix: Option<u32>,
1043 pub annotation_capture_ix: Option<u32>,
1044}
1045
1046#[derive(Debug, Clone, Copy, PartialEq)]
1047pub enum TextObject {
1048 InsideFunction,
1049 AroundFunction,
1050 InsideClass,
1051 AroundClass,
1052 InsideComment,
1053 AroundComment,
1054}
1055
1056impl TextObject {
1057 pub fn from_capture_name(name: &str) -> Option<TextObject> {
1058 match name {
1059 "function.inside" => Some(TextObject::InsideFunction),
1060 "function.around" => Some(TextObject::AroundFunction),
1061 "class.inside" => Some(TextObject::InsideClass),
1062 "class.around" => Some(TextObject::AroundClass),
1063 "comment.inside" => Some(TextObject::InsideComment),
1064 "comment.around" => Some(TextObject::AroundComment),
1065 _ => None,
1066 }
1067 }
1068
1069 pub fn around(&self) -> Option<Self> {
1070 match self {
1071 TextObject::InsideFunction => Some(TextObject::AroundFunction),
1072 TextObject::InsideClass => Some(TextObject::AroundClass),
1073 TextObject::InsideComment => Some(TextObject::AroundComment),
1074 _ => None,
1075 }
1076 }
1077}
1078
1079pub struct TextObjectConfig {
1080 pub query: Query,
1081 pub text_objects_by_capture_ix: Vec<(u32, TextObject)>,
1082}
1083
1084#[derive(Debug)]
1085pub struct EmbeddingConfig {
1086 pub query: Query,
1087 pub item_capture_ix: u32,
1088 pub name_capture_ix: Option<u32>,
1089 pub context_capture_ix: Option<u32>,
1090 pub collapse_capture_ix: Option<u32>,
1091 pub keep_capture_ix: Option<u32>,
1092}
1093
1094struct InjectionConfig {
1095 query: Query,
1096 content_capture_ix: u32,
1097 language_capture_ix: Option<u32>,
1098 patterns: Vec<InjectionPatternConfig>,
1099}
1100
1101struct RedactionConfig {
1102 pub query: Query,
1103 pub redaction_capture_ix: u32,
1104}
1105
1106#[derive(Clone, Debug, PartialEq)]
1107enum RunnableCapture {
1108 Named(SharedString),
1109 Run,
1110}
1111
1112struct RunnableConfig {
1113 pub query: Query,
1114 /// A mapping from capture indice to capture kind
1115 pub extra_captures: Vec<RunnableCapture>,
1116}
1117
1118struct OverrideConfig {
1119 query: Query,
1120 values: HashMap<u32, OverrideEntry>,
1121}
1122
1123#[derive(Debug)]
1124struct OverrideEntry {
1125 name: String,
1126 range_is_inclusive: bool,
1127 value: LanguageConfigOverride,
1128}
1129
1130#[derive(Default, Clone)]
1131struct InjectionPatternConfig {
1132 language: Option<Box<str>>,
1133 combined: bool,
1134}
1135
1136struct BracketsConfig {
1137 query: Query,
1138 open_capture_ix: u32,
1139 close_capture_ix: u32,
1140 patterns: Vec<BracketsPatternConfig>,
1141}
1142
1143#[derive(Clone, Debug, Default)]
1144struct BracketsPatternConfig {
1145 newline_only: bool,
1146}
1147
1148impl Language {
1149 pub fn new(config: LanguageConfig, ts_language: Option<tree_sitter::Language>) -> Self {
1150 Self::new_with_id(LanguageId::new(), config, ts_language)
1151 }
1152
1153 pub fn id(&self) -> LanguageId {
1154 self.id
1155 }
1156
1157 fn new_with_id(
1158 id: LanguageId,
1159 config: LanguageConfig,
1160 ts_language: Option<tree_sitter::Language>,
1161 ) -> Self {
1162 Self {
1163 id,
1164 config,
1165 grammar: ts_language.map(|ts_language| {
1166 Arc::new(Grammar {
1167 id: GrammarId::new(),
1168 highlights_query: None,
1169 brackets_config: None,
1170 outline_config: None,
1171 text_object_config: None,
1172 embedding_config: None,
1173 indents_config: None,
1174 injection_config: None,
1175 override_config: None,
1176 redactions_config: None,
1177 runnable_config: None,
1178 error_query: Query::new(&ts_language, "(ERROR) @error").ok(),
1179 ts_language,
1180 highlight_map: Default::default(),
1181 })
1182 }),
1183 context_provider: None,
1184 toolchain: None,
1185 }
1186 }
1187
1188 pub fn with_context_provider(mut self, provider: Option<Arc<dyn ContextProvider>>) -> Self {
1189 self.context_provider = provider;
1190 self
1191 }
1192
1193 pub fn with_toolchain_lister(mut self, provider: Option<Arc<dyn ToolchainLister>>) -> Self {
1194 self.toolchain = provider;
1195 self
1196 }
1197
1198 pub fn with_queries(mut self, queries: LanguageQueries) -> Result<Self> {
1199 if let Some(query) = queries.highlights {
1200 self = self
1201 .with_highlights_query(query.as_ref())
1202 .context("Error loading highlights query")?;
1203 }
1204 if let Some(query) = queries.brackets {
1205 self = self
1206 .with_brackets_query(query.as_ref())
1207 .context("Error loading brackets query")?;
1208 }
1209 if let Some(query) = queries.indents {
1210 self = self
1211 .with_indents_query(query.as_ref())
1212 .context("Error loading indents query")?;
1213 }
1214 if let Some(query) = queries.outline {
1215 self = self
1216 .with_outline_query(query.as_ref())
1217 .context("Error loading outline query")?;
1218 }
1219 if let Some(query) = queries.embedding {
1220 self = self
1221 .with_embedding_query(query.as_ref())
1222 .context("Error loading embedding query")?;
1223 }
1224 if let Some(query) = queries.injections {
1225 self = self
1226 .with_injection_query(query.as_ref())
1227 .context("Error loading injection query")?;
1228 }
1229 if let Some(query) = queries.overrides {
1230 self = self
1231 .with_override_query(query.as_ref())
1232 .context("Error loading override query")?;
1233 }
1234 if let Some(query) = queries.redactions {
1235 self = self
1236 .with_redaction_query(query.as_ref())
1237 .context("Error loading redaction query")?;
1238 }
1239 if let Some(query) = queries.runnables {
1240 self = self
1241 .with_runnable_query(query.as_ref())
1242 .context("Error loading runnables query")?;
1243 }
1244 if let Some(query) = queries.text_objects {
1245 self = self
1246 .with_text_object_query(query.as_ref())
1247 .context("Error loading textobject query")?;
1248 }
1249 Ok(self)
1250 }
1251
1252 pub fn with_highlights_query(mut self, source: &str) -> Result<Self> {
1253 let grammar = self
1254 .grammar_mut()
1255 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1256 grammar.highlights_query = Some(Query::new(&grammar.ts_language, source)?);
1257 Ok(self)
1258 }
1259
1260 pub fn with_runnable_query(mut self, source: &str) -> Result<Self> {
1261 let grammar = self
1262 .grammar_mut()
1263 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1264
1265 let query = Query::new(&grammar.ts_language, source)?;
1266 let mut extra_captures = Vec::with_capacity(query.capture_names().len());
1267
1268 for name in query.capture_names().iter() {
1269 let kind = if *name == "run" {
1270 RunnableCapture::Run
1271 } else {
1272 RunnableCapture::Named(name.to_string().into())
1273 };
1274 extra_captures.push(kind);
1275 }
1276
1277 grammar.runnable_config = Some(RunnableConfig {
1278 extra_captures,
1279 query,
1280 });
1281
1282 Ok(self)
1283 }
1284
1285 pub fn with_outline_query(mut self, source: &str) -> Result<Self> {
1286 let grammar = self
1287 .grammar_mut()
1288 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1289 let query = Query::new(&grammar.ts_language, source)?;
1290 let mut item_capture_ix = None;
1291 let mut name_capture_ix = None;
1292 let mut context_capture_ix = None;
1293 let mut extra_context_capture_ix = None;
1294 let mut open_capture_ix = None;
1295 let mut close_capture_ix = None;
1296 let mut annotation_capture_ix = None;
1297 get_capture_indices(
1298 &query,
1299 &mut [
1300 ("item", &mut item_capture_ix),
1301 ("name", &mut name_capture_ix),
1302 ("context", &mut context_capture_ix),
1303 ("context.extra", &mut extra_context_capture_ix),
1304 ("open", &mut open_capture_ix),
1305 ("close", &mut close_capture_ix),
1306 ("annotation", &mut annotation_capture_ix),
1307 ],
1308 );
1309 if let Some((item_capture_ix, name_capture_ix)) = item_capture_ix.zip(name_capture_ix) {
1310 grammar.outline_config = Some(OutlineConfig {
1311 query,
1312 item_capture_ix,
1313 name_capture_ix,
1314 context_capture_ix,
1315 extra_context_capture_ix,
1316 open_capture_ix,
1317 close_capture_ix,
1318 annotation_capture_ix,
1319 });
1320 }
1321 Ok(self)
1322 }
1323
1324 pub fn with_text_object_query(mut self, source: &str) -> Result<Self> {
1325 let grammar = self
1326 .grammar_mut()
1327 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1328 let query = Query::new(&grammar.ts_language, source)?;
1329
1330 let mut text_objects_by_capture_ix = Vec::new();
1331 for (ix, name) in query.capture_names().iter().enumerate() {
1332 if let Some(text_object) = TextObject::from_capture_name(name) {
1333 text_objects_by_capture_ix.push((ix as u32, text_object));
1334 }
1335 }
1336
1337 grammar.text_object_config = Some(TextObjectConfig {
1338 query,
1339 text_objects_by_capture_ix,
1340 });
1341 Ok(self)
1342 }
1343
1344 pub fn with_embedding_query(mut self, source: &str) -> Result<Self> {
1345 let grammar = self
1346 .grammar_mut()
1347 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1348 let query = Query::new(&grammar.ts_language, source)?;
1349 let mut item_capture_ix = None;
1350 let mut name_capture_ix = None;
1351 let mut context_capture_ix = None;
1352 let mut collapse_capture_ix = None;
1353 let mut keep_capture_ix = None;
1354 get_capture_indices(
1355 &query,
1356 &mut [
1357 ("item", &mut item_capture_ix),
1358 ("name", &mut name_capture_ix),
1359 ("context", &mut context_capture_ix),
1360 ("keep", &mut keep_capture_ix),
1361 ("collapse", &mut collapse_capture_ix),
1362 ],
1363 );
1364 if let Some(item_capture_ix) = item_capture_ix {
1365 grammar.embedding_config = Some(EmbeddingConfig {
1366 query,
1367 item_capture_ix,
1368 name_capture_ix,
1369 context_capture_ix,
1370 collapse_capture_ix,
1371 keep_capture_ix,
1372 });
1373 }
1374 Ok(self)
1375 }
1376
1377 pub fn with_brackets_query(mut self, source: &str) -> Result<Self> {
1378 let grammar = self
1379 .grammar_mut()
1380 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1381 let query = Query::new(&grammar.ts_language, source)?;
1382 let mut open_capture_ix = None;
1383 let mut close_capture_ix = None;
1384 get_capture_indices(
1385 &query,
1386 &mut [
1387 ("open", &mut open_capture_ix),
1388 ("close", &mut close_capture_ix),
1389 ],
1390 );
1391 let patterns = (0..query.pattern_count())
1392 .map(|ix| {
1393 let mut config = BracketsPatternConfig::default();
1394 for setting in query.property_settings(ix) {
1395 match setting.key.as_ref() {
1396 "newline.only" => config.newline_only = true,
1397 _ => {}
1398 }
1399 }
1400 config
1401 })
1402 .collect();
1403 if let Some((open_capture_ix, close_capture_ix)) = open_capture_ix.zip(close_capture_ix) {
1404 grammar.brackets_config = Some(BracketsConfig {
1405 query,
1406 open_capture_ix,
1407 close_capture_ix,
1408 patterns,
1409 });
1410 }
1411 Ok(self)
1412 }
1413
1414 pub fn with_indents_query(mut self, source: &str) -> Result<Self> {
1415 let grammar = self
1416 .grammar_mut()
1417 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1418 let query = Query::new(&grammar.ts_language, source)?;
1419 let mut indent_capture_ix = None;
1420 let mut start_capture_ix = None;
1421 let mut end_capture_ix = None;
1422 let mut outdent_capture_ix = None;
1423 get_capture_indices(
1424 &query,
1425 &mut [
1426 ("indent", &mut indent_capture_ix),
1427 ("start", &mut start_capture_ix),
1428 ("end", &mut end_capture_ix),
1429 ("outdent", &mut outdent_capture_ix),
1430 ],
1431 );
1432 if let Some(indent_capture_ix) = indent_capture_ix {
1433 grammar.indents_config = Some(IndentConfig {
1434 query,
1435 indent_capture_ix,
1436 start_capture_ix,
1437 end_capture_ix,
1438 outdent_capture_ix,
1439 });
1440 }
1441 Ok(self)
1442 }
1443
1444 pub fn with_injection_query(mut self, source: &str) -> Result<Self> {
1445 let grammar = self
1446 .grammar_mut()
1447 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1448 let query = Query::new(&grammar.ts_language, source)?;
1449 let mut language_capture_ix = None;
1450 let mut injection_language_capture_ix = None;
1451 let mut content_capture_ix = None;
1452 let mut injection_content_capture_ix = None;
1453 get_capture_indices(
1454 &query,
1455 &mut [
1456 ("language", &mut language_capture_ix),
1457 ("injection.language", &mut injection_language_capture_ix),
1458 ("content", &mut content_capture_ix),
1459 ("injection.content", &mut injection_content_capture_ix),
1460 ],
1461 );
1462 language_capture_ix = match (language_capture_ix, injection_language_capture_ix) {
1463 (None, Some(ix)) => Some(ix),
1464 (Some(_), Some(_)) => {
1465 return Err(anyhow!(
1466 "both language and injection.language captures are present"
1467 ));
1468 }
1469 _ => language_capture_ix,
1470 };
1471 content_capture_ix = match (content_capture_ix, injection_content_capture_ix) {
1472 (None, Some(ix)) => Some(ix),
1473 (Some(_), Some(_)) => {
1474 return Err(anyhow!(
1475 "both content and injection.content captures are present"
1476 ));
1477 }
1478 _ => content_capture_ix,
1479 };
1480 let patterns = (0..query.pattern_count())
1481 .map(|ix| {
1482 let mut config = InjectionPatternConfig::default();
1483 for setting in query.property_settings(ix) {
1484 match setting.key.as_ref() {
1485 "language" | "injection.language" => {
1486 config.language.clone_from(&setting.value);
1487 }
1488 "combined" | "injection.combined" => {
1489 config.combined = true;
1490 }
1491 _ => {}
1492 }
1493 }
1494 config
1495 })
1496 .collect();
1497 if let Some(content_capture_ix) = content_capture_ix {
1498 grammar.injection_config = Some(InjectionConfig {
1499 query,
1500 language_capture_ix,
1501 content_capture_ix,
1502 patterns,
1503 });
1504 }
1505 Ok(self)
1506 }
1507
1508 pub fn with_override_query(mut self, source: &str) -> anyhow::Result<Self> {
1509 let query = {
1510 let grammar = self
1511 .grammar
1512 .as_ref()
1513 .ok_or_else(|| anyhow!("no grammar for language"))?;
1514 Query::new(&grammar.ts_language, source)?
1515 };
1516
1517 let mut override_configs_by_id = HashMap::default();
1518 for (ix, mut name) in query.capture_names().iter().copied().enumerate() {
1519 let mut range_is_inclusive = false;
1520 if name.starts_with('_') {
1521 continue;
1522 }
1523 if let Some(prefix) = name.strip_suffix(".inclusive") {
1524 name = prefix;
1525 range_is_inclusive = true;
1526 }
1527
1528 let value = self.config.overrides.get(name).cloned().unwrap_or_default();
1529 for server_name in &value.opt_into_language_servers {
1530 if !self
1531 .config
1532 .scope_opt_in_language_servers
1533 .contains(server_name)
1534 {
1535 util::debug_panic!(
1536 "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
1537 );
1538 }
1539 }
1540
1541 override_configs_by_id.insert(
1542 ix as u32,
1543 OverrideEntry {
1544 name: name.to_string(),
1545 range_is_inclusive,
1546 value,
1547 },
1548 );
1549 }
1550
1551 let referenced_override_names = self.config.overrides.keys().chain(
1552 self.config
1553 .brackets
1554 .disabled_scopes_by_bracket_ix
1555 .iter()
1556 .flatten(),
1557 );
1558
1559 for referenced_name in referenced_override_names {
1560 if !override_configs_by_id
1561 .values()
1562 .any(|entry| entry.name == *referenced_name)
1563 {
1564 Err(anyhow!(
1565 "language {:?} has overrides in config not in query: {referenced_name:?}",
1566 self.config.name
1567 ))?;
1568 }
1569 }
1570
1571 for entry in override_configs_by_id.values_mut() {
1572 entry.value.disabled_bracket_ixs = self
1573 .config
1574 .brackets
1575 .disabled_scopes_by_bracket_ix
1576 .iter()
1577 .enumerate()
1578 .filter_map(|(ix, disabled_scope_names)| {
1579 if disabled_scope_names.contains(&entry.name) {
1580 Some(ix as u16)
1581 } else {
1582 None
1583 }
1584 })
1585 .collect();
1586 }
1587
1588 self.config.brackets.disabled_scopes_by_bracket_ix.clear();
1589
1590 let grammar = self
1591 .grammar_mut()
1592 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1593 grammar.override_config = Some(OverrideConfig {
1594 query,
1595 values: override_configs_by_id,
1596 });
1597 Ok(self)
1598 }
1599
1600 pub fn with_redaction_query(mut self, source: &str) -> anyhow::Result<Self> {
1601 let grammar = self
1602 .grammar_mut()
1603 .ok_or_else(|| anyhow!("cannot mutate grammar"))?;
1604
1605 let query = Query::new(&grammar.ts_language, source)?;
1606 let mut redaction_capture_ix = None;
1607 get_capture_indices(&query, &mut [("redact", &mut redaction_capture_ix)]);
1608
1609 if let Some(redaction_capture_ix) = redaction_capture_ix {
1610 grammar.redactions_config = Some(RedactionConfig {
1611 query,
1612 redaction_capture_ix,
1613 });
1614 }
1615
1616 Ok(self)
1617 }
1618
1619 fn grammar_mut(&mut self) -> Option<&mut Grammar> {
1620 Arc::get_mut(self.grammar.as_mut()?)
1621 }
1622
1623 pub fn name(&self) -> LanguageName {
1624 self.config.name.clone()
1625 }
1626
1627 pub fn code_fence_block_name(&self) -> Arc<str> {
1628 self.config
1629 .code_fence_block_name
1630 .clone()
1631 .unwrap_or_else(|| self.config.name.as_ref().to_lowercase().into())
1632 }
1633
1634 pub fn context_provider(&self) -> Option<Arc<dyn ContextProvider>> {
1635 self.context_provider.clone()
1636 }
1637
1638 pub fn toolchain_lister(&self) -> Option<Arc<dyn ToolchainLister>> {
1639 self.toolchain.clone()
1640 }
1641
1642 pub fn highlight_text<'a>(
1643 self: &'a Arc<Self>,
1644 text: &'a Rope,
1645 range: Range<usize>,
1646 ) -> Vec<(Range<usize>, HighlightId)> {
1647 let mut result = Vec::new();
1648 if let Some(grammar) = &self.grammar {
1649 let tree = grammar.parse_text(text, None);
1650 let captures =
1651 SyntaxSnapshot::single_tree_captures(range.clone(), text, &tree, self, |grammar| {
1652 grammar.highlights_query.as_ref()
1653 });
1654 let highlight_maps = vec![grammar.highlight_map()];
1655 let mut offset = 0;
1656 for chunk in
1657 BufferChunks::new(text, range, Some((captures, highlight_maps)), false, None)
1658 {
1659 let end_offset = offset + chunk.text.len();
1660 if let Some(highlight_id) = chunk.syntax_highlight_id {
1661 if !highlight_id.is_default() {
1662 result.push((offset..end_offset, highlight_id));
1663 }
1664 }
1665 offset = end_offset;
1666 }
1667 }
1668 result
1669 }
1670
1671 pub fn path_suffixes(&self) -> &[String] {
1672 &self.config.matcher.path_suffixes
1673 }
1674
1675 pub fn should_autoclose_before(&self, c: char) -> bool {
1676 c.is_whitespace() || self.config.autoclose_before.contains(c)
1677 }
1678
1679 pub fn set_theme(&self, theme: &SyntaxTheme) {
1680 if let Some(grammar) = self.grammar.as_ref() {
1681 if let Some(highlights_query) = &grammar.highlights_query {
1682 *grammar.highlight_map.lock() =
1683 HighlightMap::new(highlights_query.capture_names(), theme);
1684 }
1685 }
1686 }
1687
1688 pub fn grammar(&self) -> Option<&Arc<Grammar>> {
1689 self.grammar.as_ref()
1690 }
1691
1692 pub fn default_scope(self: &Arc<Self>) -> LanguageScope {
1693 LanguageScope {
1694 language: self.clone(),
1695 override_id: None,
1696 }
1697 }
1698
1699 pub fn lsp_id(&self) -> String {
1700 self.config.name.lsp_id()
1701 }
1702
1703 pub fn prettier_parser_name(&self) -> Option<&str> {
1704 self.config.prettier_parser_name.as_deref()
1705 }
1706
1707 pub fn config(&self) -> &LanguageConfig {
1708 &self.config
1709 }
1710}
1711
1712impl LanguageScope {
1713 pub fn path_suffixes(&self) -> &[String] {
1714 &self.language.path_suffixes()
1715 }
1716
1717 pub fn language_name(&self) -> LanguageName {
1718 self.language.config.name.clone()
1719 }
1720
1721 pub fn collapsed_placeholder(&self) -> &str {
1722 self.language.config.collapsed_placeholder.as_ref()
1723 }
1724
1725 /// Returns line prefix that is inserted in e.g. line continuations or
1726 /// in `toggle comments` action.
1727 pub fn line_comment_prefixes(&self) -> &[Arc<str>] {
1728 Override::as_option(
1729 self.config_override().map(|o| &o.line_comments),
1730 Some(&self.language.config.line_comments),
1731 )
1732 .map_or([].as_slice(), |e| e.as_slice())
1733 }
1734
1735 pub fn block_comment_delimiters(&self) -> Option<(&Arc<str>, &Arc<str>)> {
1736 Override::as_option(
1737 self.config_override().map(|o| &o.block_comment),
1738 self.language.config.block_comment.as_ref(),
1739 )
1740 .map(|e| (&e.0, &e.1))
1741 }
1742
1743 /// Returns a list of language-specific word characters.
1744 ///
1745 /// By default, Zed treats alphanumeric characters (and '_') as word characters for
1746 /// the purpose of actions like 'move to next word end` or whole-word search.
1747 /// It additionally accounts for language's additional word characters.
1748 pub fn word_characters(&self) -> Option<&HashSet<char>> {
1749 Override::as_option(
1750 self.config_override().map(|o| &o.word_characters),
1751 Some(&self.language.config.word_characters),
1752 )
1753 }
1754
1755 /// Returns a list of language-specific characters that are considered part of
1756 /// a completion query.
1757 pub fn completion_query_characters(&self) -> Option<&HashSet<char>> {
1758 Override::as_option(
1759 self.config_override()
1760 .map(|o| &o.completion_query_characters),
1761 Some(&self.language.config.completion_query_characters),
1762 )
1763 }
1764
1765 /// Returns a list of bracket pairs for a given language with an additional
1766 /// piece of information about whether the particular bracket pair is currently active for a given language.
1767 pub fn brackets(&self) -> impl Iterator<Item = (&BracketPair, bool)> {
1768 let mut disabled_ids = self
1769 .config_override()
1770 .map_or(&[] as _, |o| o.disabled_bracket_ixs.as_slice());
1771 self.language
1772 .config
1773 .brackets
1774 .pairs
1775 .iter()
1776 .enumerate()
1777 .map(move |(ix, bracket)| {
1778 let mut is_enabled = true;
1779 if let Some(next_disabled_ix) = disabled_ids.first() {
1780 if ix == *next_disabled_ix as usize {
1781 disabled_ids = &disabled_ids[1..];
1782 is_enabled = false;
1783 }
1784 }
1785 (bracket, is_enabled)
1786 })
1787 }
1788
1789 pub fn should_autoclose_before(&self, c: char) -> bool {
1790 c.is_whitespace() || self.language.config.autoclose_before.contains(c)
1791 }
1792
1793 pub fn language_allowed(&self, name: &LanguageServerName) -> bool {
1794 let config = &self.language.config;
1795 let opt_in_servers = &config.scope_opt_in_language_servers;
1796 if opt_in_servers.iter().any(|o| *o == *name) {
1797 if let Some(over) = self.config_override() {
1798 over.opt_into_language_servers.iter().any(|o| *o == *name)
1799 } else {
1800 false
1801 }
1802 } else {
1803 true
1804 }
1805 }
1806
1807 pub fn override_name(&self) -> Option<&str> {
1808 let id = self.override_id?;
1809 let grammar = self.language.grammar.as_ref()?;
1810 let override_config = grammar.override_config.as_ref()?;
1811 override_config.values.get(&id).map(|e| e.name.as_str())
1812 }
1813
1814 fn config_override(&self) -> Option<&LanguageConfigOverride> {
1815 let id = self.override_id?;
1816 let grammar = self.language.grammar.as_ref()?;
1817 let override_config = grammar.override_config.as_ref()?;
1818 override_config.values.get(&id).map(|e| &e.value)
1819 }
1820}
1821
1822impl Hash for Language {
1823 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1824 self.id.hash(state)
1825 }
1826}
1827
1828impl PartialEq for Language {
1829 fn eq(&self, other: &Self) -> bool {
1830 self.id.eq(&other.id)
1831 }
1832}
1833
1834impl Eq for Language {}
1835
1836impl Debug for Language {
1837 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1838 f.debug_struct("Language")
1839 .field("name", &self.config.name)
1840 .finish()
1841 }
1842}
1843
1844impl Grammar {
1845 pub fn id(&self) -> GrammarId {
1846 self.id
1847 }
1848
1849 fn parse_text(&self, text: &Rope, old_tree: Option<Tree>) -> Tree {
1850 with_parser(|parser| {
1851 parser
1852 .set_language(&self.ts_language)
1853 .expect("incompatible grammar");
1854 let mut chunks = text.chunks_in_range(0..text.len());
1855 parser
1856 .parse_with_options(
1857 &mut move |offset, _| {
1858 chunks.seek(offset);
1859 chunks.next().unwrap_or("").as_bytes()
1860 },
1861 old_tree.as_ref(),
1862 None,
1863 )
1864 .unwrap()
1865 })
1866 }
1867
1868 pub fn highlight_map(&self) -> HighlightMap {
1869 self.highlight_map.lock().clone()
1870 }
1871
1872 pub fn highlight_id_for_name(&self, name: &str) -> Option<HighlightId> {
1873 let capture_id = self
1874 .highlights_query
1875 .as_ref()?
1876 .capture_index_for_name(name)?;
1877 Some(self.highlight_map.lock().get(capture_id))
1878 }
1879}
1880
1881impl CodeLabel {
1882 pub fn fallback_for_completion(
1883 item: &lsp::CompletionItem,
1884 language: Option<&Language>,
1885 ) -> Self {
1886 let highlight_id = item.kind.and_then(|kind| {
1887 let grammar = language?.grammar()?;
1888 use lsp::CompletionItemKind as Kind;
1889 match kind {
1890 Kind::CLASS => grammar.highlight_id_for_name("type"),
1891 Kind::CONSTANT => grammar.highlight_id_for_name("constant"),
1892 Kind::CONSTRUCTOR => grammar.highlight_id_for_name("constructor"),
1893 Kind::ENUM => grammar
1894 .highlight_id_for_name("enum")
1895 .or_else(|| grammar.highlight_id_for_name("type")),
1896 Kind::FIELD => grammar.highlight_id_for_name("property"),
1897 Kind::FUNCTION => grammar.highlight_id_for_name("function"),
1898 Kind::INTERFACE => grammar.highlight_id_for_name("type"),
1899 Kind::METHOD => grammar
1900 .highlight_id_for_name("function.method")
1901 .or_else(|| grammar.highlight_id_for_name("function")),
1902 Kind::OPERATOR => grammar.highlight_id_for_name("operator"),
1903 Kind::PROPERTY => grammar.highlight_id_for_name("property"),
1904 Kind::STRUCT => grammar.highlight_id_for_name("type"),
1905 Kind::VARIABLE => grammar.highlight_id_for_name("variable"),
1906 Kind::KEYWORD => grammar.highlight_id_for_name("keyword"),
1907 _ => None,
1908 }
1909 });
1910
1911 let label = &item.label;
1912 let label_length = label.len();
1913 let runs = highlight_id
1914 .map(|highlight_id| vec![(0..label_length, highlight_id)])
1915 .unwrap_or_default();
1916 let text = if let Some(detail) = &item.detail {
1917 format!("{label} {detail}")
1918 } else if let Some(description) = item
1919 .label_details
1920 .as_ref()
1921 .and_then(|label_details| label_details.description.as_ref())
1922 {
1923 format!("{label} {description}")
1924 } else {
1925 label.clone()
1926 };
1927 Self {
1928 text,
1929 runs,
1930 filter_range: 0..label_length,
1931 }
1932 }
1933
1934 pub fn plain(text: String, filter_text: Option<&str>) -> Self {
1935 let mut result = Self {
1936 runs: Vec::new(),
1937 filter_range: 0..text.len(),
1938 text,
1939 };
1940 if let Some(filter_text) = filter_text {
1941 if let Some(ix) = result.text.find(filter_text) {
1942 result.filter_range = ix..ix + filter_text.len();
1943 }
1944 }
1945 result
1946 }
1947
1948 pub fn push_str(&mut self, text: &str, highlight: Option<HighlightId>) {
1949 let start_ix = self.text.len();
1950 self.text.push_str(text);
1951 let end_ix = self.text.len();
1952 if let Some(highlight) = highlight {
1953 self.runs.push((start_ix..end_ix, highlight));
1954 }
1955 }
1956
1957 pub fn text(&self) -> &str {
1958 self.text.as_str()
1959 }
1960
1961 pub fn filter_text(&self) -> &str {
1962 &self.text[self.filter_range.clone()]
1963 }
1964}
1965
1966impl From<String> for CodeLabel {
1967 fn from(value: String) -> Self {
1968 Self::plain(value, None)
1969 }
1970}
1971
1972impl From<&str> for CodeLabel {
1973 fn from(value: &str) -> Self {
1974 Self::plain(value.to_string(), None)
1975 }
1976}
1977
1978impl Ord for LanguageMatcher {
1979 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1980 self.path_suffixes.cmp(&other.path_suffixes).then_with(|| {
1981 self.first_line_pattern
1982 .as_ref()
1983 .map(Regex::as_str)
1984 .cmp(&other.first_line_pattern.as_ref().map(Regex::as_str))
1985 })
1986 }
1987}
1988
1989impl PartialOrd for LanguageMatcher {
1990 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1991 Some(self.cmp(other))
1992 }
1993}
1994
1995impl Eq for LanguageMatcher {}
1996
1997impl PartialEq for LanguageMatcher {
1998 fn eq(&self, other: &Self) -> bool {
1999 self.path_suffixes == other.path_suffixes
2000 && self.first_line_pattern.as_ref().map(Regex::as_str)
2001 == other.first_line_pattern.as_ref().map(Regex::as_str)
2002 }
2003}
2004
2005#[cfg(any(test, feature = "test-support"))]
2006impl Default for FakeLspAdapter {
2007 fn default() -> Self {
2008 Self {
2009 name: "the-fake-language-server",
2010 capabilities: lsp::LanguageServer::full_capabilities(),
2011 initializer: None,
2012 disk_based_diagnostics_progress_token: None,
2013 initialization_options: None,
2014 disk_based_diagnostics_sources: Vec::new(),
2015 prettier_plugins: Vec::new(),
2016 language_server_binary: LanguageServerBinary {
2017 path: "/the/fake/lsp/path".into(),
2018 arguments: vec![],
2019 env: Default::default(),
2020 },
2021 label_for_completion: None,
2022 }
2023 }
2024}
2025
2026#[cfg(any(test, feature = "test-support"))]
2027#[async_trait(?Send)]
2028impl LspAdapter for FakeLspAdapter {
2029 fn name(&self) -> LanguageServerName {
2030 LanguageServerName(self.name.into())
2031 }
2032
2033 async fn check_if_user_installed(
2034 &self,
2035 _: &dyn LspAdapterDelegate,
2036 _: Arc<dyn LanguageToolchainStore>,
2037 _: &AsyncApp,
2038 ) -> Option<LanguageServerBinary> {
2039 Some(self.language_server_binary.clone())
2040 }
2041
2042 fn get_language_server_command<'a>(
2043 self: Arc<Self>,
2044 _: Arc<dyn LspAdapterDelegate>,
2045 _: Arc<dyn LanguageToolchainStore>,
2046 _: LanguageServerBinaryOptions,
2047 _: futures::lock::MutexGuard<'a, Option<LanguageServerBinary>>,
2048 _: &'a mut AsyncApp,
2049 ) -> Pin<Box<dyn 'a + Future<Output = Result<LanguageServerBinary>>>> {
2050 async move { Ok(self.language_server_binary.clone()) }.boxed_local()
2051 }
2052
2053 async fn fetch_latest_server_version(
2054 &self,
2055 _: &dyn LspAdapterDelegate,
2056 ) -> Result<Box<dyn 'static + Send + Any>> {
2057 unreachable!();
2058 }
2059
2060 async fn fetch_server_binary(
2061 &self,
2062 _: Box<dyn 'static + Send + Any>,
2063 _: PathBuf,
2064 _: &dyn LspAdapterDelegate,
2065 ) -> Result<LanguageServerBinary> {
2066 unreachable!();
2067 }
2068
2069 async fn cached_server_binary(
2070 &self,
2071 _: PathBuf,
2072 _: &dyn LspAdapterDelegate,
2073 ) -> Option<LanguageServerBinary> {
2074 unreachable!();
2075 }
2076
2077 fn disk_based_diagnostic_sources(&self) -> Vec<String> {
2078 self.disk_based_diagnostics_sources.clone()
2079 }
2080
2081 fn disk_based_diagnostics_progress_token(&self) -> Option<String> {
2082 self.disk_based_diagnostics_progress_token.clone()
2083 }
2084
2085 async fn initialization_options(
2086 self: Arc<Self>,
2087 _: &dyn Fs,
2088 _: &Arc<dyn LspAdapterDelegate>,
2089 ) -> Result<Option<Value>> {
2090 Ok(self.initialization_options.clone())
2091 }
2092
2093 async fn label_for_completion(
2094 &self,
2095 item: &lsp::CompletionItem,
2096 language: &Arc<Language>,
2097 ) -> Option<CodeLabel> {
2098 let label_for_completion = self.label_for_completion.as_ref()?;
2099 label_for_completion(item, language)
2100 }
2101}
2102
2103fn get_capture_indices(query: &Query, captures: &mut [(&str, &mut Option<u32>)]) {
2104 for (ix, name) in query.capture_names().iter().enumerate() {
2105 for (capture_name, index) in captures.iter_mut() {
2106 if capture_name == name {
2107 **index = Some(ix as u32);
2108 break;
2109 }
2110 }
2111 }
2112}
2113
2114pub fn point_to_lsp(point: PointUtf16) -> lsp::Position {
2115 lsp::Position::new(point.row, point.column)
2116}
2117
2118pub fn point_from_lsp(point: lsp::Position) -> Unclipped<PointUtf16> {
2119 Unclipped(PointUtf16::new(point.line, point.character))
2120}
2121
2122pub fn range_to_lsp(range: Range<PointUtf16>) -> Result<lsp::Range> {
2123 if range.start > range.end {
2124 Err(anyhow!(
2125 "Inverted range provided to an LSP request: {:?}-{:?}",
2126 range.start,
2127 range.end
2128 ))
2129 } else {
2130 Ok(lsp::Range {
2131 start: point_to_lsp(range.start),
2132 end: point_to_lsp(range.end),
2133 })
2134 }
2135}
2136
2137pub fn range_from_lsp(range: lsp::Range) -> Range<Unclipped<PointUtf16>> {
2138 let mut start = point_from_lsp(range.start);
2139 let mut end = point_from_lsp(range.end);
2140 if start > end {
2141 log::warn!("range_from_lsp called with inverted range {start:?}-{end:?}");
2142 mem::swap(&mut start, &mut end);
2143 }
2144 start..end
2145}
2146
2147#[cfg(test)]
2148mod tests {
2149 use super::*;
2150 use gpui::TestAppContext;
2151
2152 #[gpui::test(iterations = 10)]
2153 async fn test_language_loading(cx: &mut TestAppContext) {
2154 let languages = LanguageRegistry::test(cx.executor());
2155 let languages = Arc::new(languages);
2156 languages.register_native_grammars([
2157 ("json", tree_sitter_json::LANGUAGE),
2158 ("rust", tree_sitter_rust::LANGUAGE),
2159 ]);
2160 languages.register_test_language(LanguageConfig {
2161 name: "JSON".into(),
2162 grammar: Some("json".into()),
2163 matcher: LanguageMatcher {
2164 path_suffixes: vec!["json".into()],
2165 ..Default::default()
2166 },
2167 ..Default::default()
2168 });
2169 languages.register_test_language(LanguageConfig {
2170 name: "Rust".into(),
2171 grammar: Some("rust".into()),
2172 matcher: LanguageMatcher {
2173 path_suffixes: vec!["rs".into()],
2174 ..Default::default()
2175 },
2176 ..Default::default()
2177 });
2178 assert_eq!(
2179 languages.language_names(),
2180 &[
2181 "JSON".to_string(),
2182 "Plain Text".to_string(),
2183 "Rust".to_string(),
2184 ]
2185 );
2186
2187 let rust1 = languages.language_for_name("Rust");
2188 let rust2 = languages.language_for_name("Rust");
2189
2190 // Ensure language is still listed even if it's being loaded.
2191 assert_eq!(
2192 languages.language_names(),
2193 &[
2194 "JSON".to_string(),
2195 "Plain Text".to_string(),
2196 "Rust".to_string(),
2197 ]
2198 );
2199
2200 let (rust1, rust2) = futures::join!(rust1, rust2);
2201 assert!(Arc::ptr_eq(&rust1.unwrap(), &rust2.unwrap()));
2202
2203 // Ensure language is still listed even after loading it.
2204 assert_eq!(
2205 languages.language_names(),
2206 &[
2207 "JSON".to_string(),
2208 "Plain Text".to_string(),
2209 "Rust".to_string(),
2210 ]
2211 );
2212
2213 // Loading an unknown language returns an error.
2214 assert!(languages.language_for_name("Unknown").await.is_err());
2215 }
2216}