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