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