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